1

I'm trying to use a modal operator timer to get a piece of code to execute every 5 seconds. Currently all i want is for it to print a statement every 5 seconds however, in the future, this will be changed to create a new object every 5 seconds.

Currently i use the following which prints the statement multiple times a second.

import bpy

class ModalTimerOperator(bpy.types.Operator): """Operator which runs its self from a timer""" bl_idname = "wm.modal_timer_operator" bl_label = "Modal Timer Operator"

_timer = None

def modal(self, context, event):
    if event.type in {'RIGHTMOUSE', 'ESC'}:
        self.cancel(context)
        return {'CANCELLED'}

    if event.type == 'TIMER':
        print("5 seconds has passed")

    return {'PASS_THROUGH'}

def execute(self, context):
    wm = context.window_manager
    self._timer = wm.event_timer_add(1.0, window=context.window)
    wm.modal_handler_add(self)
    return {'RUNNING_MODAL'}

def cancel(self, context):
    wm = context.window_manager
    wm.event_timer_remove(self._timer)


def register(): bpy.utils.register_class(ModalTimerOperator)

def unregister(): bpy.utils.unregister_class(ModalTimerOperator)

if name == "main": register()

# test call
bpy.ops.wm.modal_timer_operator()

How do i change this to run once every 5 seconds?

Bob
  • 51
  • 3

1 Answers1

1

The event timer has a property which defines how often your modal function will get called with the timer event, just change the value accordingly in the execute function:

time = 5.0
self._timer = wm.event_timer_add(time, window=context.window)
Sanoronas
  • 146
  • 5
  • 1
    how often the modal is called or when timer event is true? – batFINGER May 20 '21 at 12:21
  • it will get called for every occuring event (such as ESC for cancelling), but only every 5 seconds from the timer event – Sanoronas May 20 '21 at 12:29
  • To clarify re comment: If a print("bar") is added under def modal(... and a print("foo") in if event.type == 'TIMER' it will print a lot of bars between each foo. Feel that your answer is implying modal is being called every 5 secs which AFAIC is not the case. – batFINGER May 20 '21 at 12:38
  • you're right, modal gets called more often. I included the timer event in my answer, is that enough? – Sanoronas May 20 '21 at 12:56