4
$\begingroup$

How do you clear all timers in bpy.app.timers? It seems like there is no straightforward way, if not impossible, to clear timers that have run from previous script execution. It is easy to do for bpy.app.handlers, you just call the clear() function of the handler.

import bpy

bpy.app.handlers.frame_change_post.clear() # easy clear everything from previous execution as well
bpy.app.timers.clear() # but this does not exist

def some_handler(scene, depsgraph):
    print("some_handler", scene, depsgraph)

def some_timer():
    print("some_timer")
    return 2.0

bpy.app.handlers.frame_change_post.append(some_handler)
bpy.app.timers.register(some_timer)

And of course you can't clear a previous some_timer function using bpy.app.timers.unregister(some_timer) from a previous execution because that function will have another pointer address <function some_timer at 0x00000000XXXXXXXX>

Current workaround is to close the file and re-open the file or open a new one. Is there any fix or any other workaround for this so I don't have to close the file?

$\endgroup$
2
  • 1
    $\begingroup$ Perhaps find a place to store that function address explicitly like bpy.__some_timer and retrieve it later run of the script? $\endgroup$
    – HikariTW
    Commented Jan 15, 2023 at 1:09
  • 1
    $\begingroup$ @HikariTW holy cow it works! thank you so much! $\endgroup$
    – Harry McKenzie
    Commented Jan 19, 2023 at 11:24

1 Answer 1

4
$\begingroup$

Thanks to @HikariTW for the current workaround, which is to save the function pointer of the timer callback into an attribute appended to the bpy module, albeit potentially considered namespace pollution:

import bpy

try:
    bpy.app.timers.unregister(bpy.some_timer_function_pointer)
except:
    pass

def some_timer():
    print("some_timer")
    return 2.0

bpy.app.timers.register(some_timer)
bpy.some_timer_function_pointer = some_timer

Anything stored in an attribute appended to the bpy module, will still exist on a script re-run.

$\endgroup$
2
  • 2
    $\begingroup$ Mandatory avoid bare try: except:, always catch exactly the exceptions you know you'll be catching, otherwise other types of exceptions will be silenced. Here I think it's a RuntimeError ? $\endgroup$
    – Gorgious
    Commented Jan 19, 2023 at 12:19
  • 1
    $\begingroup$ yes that is correct. actually i used hasattr(bpy, 'some_timer_function_pointer') at first. but decided to make it shorter just for demo purposes :) $\endgroup$
    – Harry McKenzie
    Commented Jan 19, 2023 at 12:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .