Modal Timer Operator.
For original code, the operator will never be called. Putting a print in the if statement will show it is never run. If the if clause was true; operator would be called once, when the script is run or imported. It is not run again when the timer method is called after 5 seconds. Suggest googling (stackoverflow) "python variable scope". I imagine this is why @lemon edited, thinking it may be a pasting error.
However the @lemon edited script with indent wont work see: Context is incorrect when calling from a timer
Instead could use a modal timer operator, when a number of seconds has elapsed, call the add primitive cube operator and finish.
How to run a python script at regular intervals?
Edited version of Text Editor > Templates > Python > Operator Modal Timer
import bpy
from bpy.props import IntProperty
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
delay: IntProperty(
name="Delay",
default=10,
)
def modal(self, context, event):
if event.type == 'TIMER':
if self._timer.time_duration >= self.delay:
print(
"Cube added after ",
self._timer.time_duration,
"secs")
# remove timer
self.cancel(context)
# call the operator, return its status
return bpy.ops.mesh.primitive_cube_add()
return {'PASS_THROUGH'}
def execute(self, context):
wm = context.window_manager
self._timer = wm.event_timer_add(self.delay, 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(delay=5)
Test run
Cube added after 5.001951217651367 secs
print(context.copy())and will notice many not available ie haveNonevalues when run from a timer thread. See https://blender.stackexchange.com/questions/135970/context-is-incorrect-when-calling-from-a-timer See the modal timer template in text editor for another way to wait to delay an operator running which will have context. – batFINGER Sep 17 '20 at 14:58