/blender-developer-tools:timers-modal-and-threadingfrom blender-developer-tools
Guides writing Blender add-ons that use timers, modal operators, and worker threads without freezing or crashing. Covers bpy.app.timers return values, persistent=True, event_timer_add, and thread-safe result queues.
Ships in blender-developer-tools. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Use this skill when the user:
bpy from a threading.Thread and gets crashes or corrupted datablender --background and it never runswm.read_homefile--background) or in a windowed BlenderTimers, modal operators and event_timer_add are all driven by Blender's window-manager event loop. A windowed Blender has one. blender --background --python script.py does not: the script runs, Blender exits, and a registered timer never runs (measured on 4.5.11, 5.1.2 and 5.2.1: is_registered is True and the callback never executes). Headless work must run synchronously in the script; there is no deferred callback to wait for.
bpy.app.timers: the return value schedules the next runimport bpy
def poll():
if done():
return None # unregister: this was the last run
return 0.5 # run again in 0.5 s
bpy.app.timers.register(poll, first_interval=0.5)
None unregisters; a float re-runs after that many seconds. Measured in a windowed child: a None timer ran once, and one returning 0.05 until its third call ran exactly three times. Afterwards is_registered was False for both.0.0 does not mean "stop": it re-runs on the next event-loop pass. A timer meant to run once that returns 0.0 ran 21 times on 4.5.11 and 30 on 5.2.1 before a file load removed it.first_interval is keyword-only: register(poll, 0.5) raises TypeError: register() takes exactly 1 positional argument (2 given) on 4.5.11, 5.1.2 and 5.2.1.persistent=True. Measured: after wm.read_factory_settings inside a timer, the persistent timer was still registered and the plain one was not. Add-on services that must outlive File → Open need persistent=True. Per-file work should be plain, so it does not leak into the next file.unregister(): if bpy.app.timers.is_registered(poll): bpy.app.timers.unregister(poll).bpy on itbpy is not thread-safe. A worker thread may compute, download or read files, but every bpy read and write happens on the main thread. Hand results over through a queue.Queue, and drain it from a timer:
import queue
import threading
import bpy
results = queue.Queue()
pending = 0 # jobs started, not yet drained (main thread only)
def worker(url):
try:
results.put((True, download(url))) # no bpy here
except BaseException as e:
results.put((False, e)) # always put, or the drain waits forever
def drain():
global pending
while True: # take everything that landed this tick
try:
ok, value = results.get_nowait()
except queue.Empty:
break
pending -= 1
if ok:
apply_to_scene(value) # bpy, on the main thread
else:
print(f"download failed: {value!r}")
return 0.1 if pending else None # stop only when every job is in
def start(url):
global pending
pending += 1
threading.Thread(target=worker, args=(url,), daemon=True).start()
if not bpy.app.timers.is_registered(drain):
bpy.app.timers.register(drain, first_interval=0.1)
Two traps in the one-shot version (get_nowait() once, then return None):
None after one result, one of two results was applied. Count pending jobs and unregister only at 0.put(). Measured: the pending count stayed at 1 and the drain was still registered seconds later, and no error was reported anywhere but the thread's traceback. Wrap the job and put the exception, so the main thread can report it.A third trap appears when the user opens another file while jobs run. File → Open drops the plain drain timer, but the worker threads keep running and keep putting results. The next start() registers the drain again, and that drain applies every queued result, including the old file's, to the new file's bpy.data. Measured on 5.2.1 and 4.5.14: a job started before wm.read_homefile wrote its result onto the new file's Target object. The snippet tags each job with an epoch, and a @persistent load_post handler bumps the epoch and resets pending. The drain then discards results from older epochs: with the epoch check in place, the stale result was dropped and a job started after the load still applied. Register that handler in register() and remove it in unregister(). Making the drain persistent=True is the wrong fix here: it keeps the timer alive across the load, but still applies the old file's results.
Measured with three concurrent jobs, one raising ValueError: both results were applied, the error was reported, the pending count reached 0, and the drain unregistered itself. Every result was handled on the script's main-thread threading.get_ident(), which no worker shared. Compare idents to prove that: threading.current_thread() is threading.main_thread() checked inside a timer is always true, because timers only run on the main thread. Use daemon=True so a hung worker cannot keep Blender from quitting. For network work, check bpy.app.online_access first (see extension-runtime-and-packaging).
event_timer_add plus modal()class MYADDON_OT_watch(bpy.types.Operator):
bl_idname = "myaddon.watch"
bl_label = "Watch"
_timer = None
def invoke(self, context, event):
wm = context.window_manager
self._timer = wm.event_timer_add(0.1, window=context.window)
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def modal(self, context, event):
if event.type == 'ESC':
self.cancel(context)
return {'CANCELLED'}
if event.type != 'TIMER':
return {'PASS_THROUGH'} # let the UI keep working
if step(context): # True when the job is done
self.cancel(context)
return {'FINISHED'}
return {'RUNNING_MODAL'}
def cancel(self, context):
if self._timer is not None:
context.window_manager.event_timer_remove(self._timer)
self._timer = None
{'PASS_THROUGH'} for events you do not handle, or the operator swallows all input and the UI looks frozen.bpy.types.Event has no timer attribute (absent from its RNA on 4.5.11 and 5.2.1). event.timer is self._timer raises AttributeError inside modal(). Test event.type == 'TIMER'; if several timers feed one operator, count or time the ticks yourself.FINISHED and CANCELLED returns, and cancel(), which Blender calls when it ends a running modal operator itself.invoke returned {'RUNNING_MODAL'}, modal() received three TIMER events, then returned {'FINISHED'} and removed its timer.with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): bpy.ops.myaddon.watch('INVOKE_DEFAULT').For a progress readout, call context.window_manager.progress_begin(0, total), progress_update(i) and progress_end() from the main thread: the modal step or the drain timer, never the worker.
bpy from a worker thread (bpy.data.objects.new inside Thread.run). Compute in the thread; apply on the main thread from a timer.time.sleep() or a while loop in an operator to wait for work. It blocks the event loop. Use a timer or a modal operator.--background. There is no event loop; run the work directly in the script.0. Zero means "again on the next pass"; return None to stop.bpy.app.timers.register(fn, 1.0). first_interval is keyword-only on every supported version.persistent=True. They vanish on the first File → Open.event.timer in modal(). The attribute does not exist; test event.type == 'TIMER'.cancel() and on every return that ends the operator.The behaviour above was measured identically on 4.5 LTS, 5.1 and 5.2 LTS. The only visible difference is cosmetic: 5.2's docstring shows register(function, *, first_interval=0, persistent=False), while 4.5 documents the same keyword-only call without the *. No version branch is needed.
operators: operator lifecycle, bl_options, invoke versus executedrivers-and-app-handlers: @persistent application handlers, the other way to react to file loadsheadless-batch-scripting: what to do instead when there is no event loopextension-runtime-and-packaging: bpy.app.online_access before network work in a workersnippets/thread-queue-timer.pyEach example runs headless, asserts the contract, and exits non-zero when it breaks. Run one with blender --background --python <script> --; pass a falsifier flag to watch the check fail.
timers-modal-threading: Proves the event-loop contracts behind long-running add-on work. Falsify: --windowed-background-child (exit 3).Short standalone patterns to copy. Each one runs in CI on 5.2 and 4.5 with a check and a falsifier.
bpy.app.timers: https://docs.blender.org/api/current/bpy.app.timers.htmlWindowManager.event_timer_add: https://docs.blender.org/api/current/bpy.types.WindowManager.html#bpy.types.WindowManager.event_timer_addWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub tmhsdigital/blender-developer-tools --plugin blender-developer-tools27 skills in this plugin
/addon-scaffoldingScaffold a Blender add-on as an Extensions Platform package: blender_manifest.toml, modular file layout, register_classes_factory, symmetric register/unregister. Use when the user starts a new add-on or extension, writes or fixes blender_manifest.toml, asks which layout or registration pattern to use on Blender 4.5 LTS or 5.x, or has classes that fail to register or unregister cleanly. Targets 5.2 LTS with 4.5 LTS fallback./ai-mesh-cleanupOrdered cleanup for an imported generated or scanned mesh before it goes to an engine: scene units, apply rotation and scale, origin to base, recalculate normals, evaluated triangle count, decimate to a budget, convex collider. Use when the user has a GLB, glTF or FBX that is not engine-ready, mentions unit scale, unapplied transforms, triangle budget, LODs or a collision hull, or is about to run mesh operations on an import without checking its scale. Targets 5.2 LTS with 4.5 LTS fallback./bake-high-to-lowCage-bake high-poly surface detail onto a low-poly target as a tangent-space normal map with bpy.ops.object.bake (Cycles, selected-to-active, active Image Texture node, UV layer, save_render). Use when the user wants a normal map from a dense mesh onto a game-resolution or decimated LOD, mentions cage_extrusion or use_selected_to_active, or gets a bake that returns CANCELLED, comes out black or flat, or fails with 'No active UV layer found'. Targets 5.2 LTS with 4.5 LTS fallback./blender-rulesBlender Python anti-pattern rules (bmesh leaks, bpy.ops in loops, deprecated context-copy overrides, bulk mesh writes, prop annotations and context guards, Extensions manifest, import scale, export modifiers, glTF/FBX axis RNA, the removed bgl module, the normals API removed in 4.1). Use when writing, reviewing or fixing any bpy / Blender add-on or script code./bl-info-migrationMigrate a legacy bl_info add-on to the Extensions Platform in three steps, with a before/after diff and the dual-format pattern. Use when the user has a bl_info dictionary in __init__.py, asks whether bl_info is deprecated or still supported, wants to publish to extensions.blender.org or ship an extension .zip, or sees warnings about legacy add-ons at install time. Targets 5.2 LTS; manifests work from 4.2./compositor-nodesBuild and render through the scene compositor from Python across the 4.5 LTS to 5.x split: scene.use_nodes plus scene.node_tree and a Composite node on 4.5, a CompositorNodeTree node group assigned to scene.compositing_node_group with interface sockets and a Group Output on 5.x, a Render Layers to Glare (Fog Glow) chain, the Glare node's move from enum properties to menu input sockets, and render.use_compositing. Use when the user scripts compositor nodes, adds bloom or glow, hits AttributeError on scene.node_tree in 5.x, sets glare_type or quality and gets AttributeError on 5.x, looks for the removed EEVEE use_bloom toggle, or renders and sees no compositor effect. Targets 5.2 LTS with 4.5 LTS fallback.Other plugins' skills for the same job