Search code examples
pythonpywin32windows-task-scheduler

How do I create a scheduled task using Python Win32com that runs every 5 seconds?


I am trying to create a scheduled task in Python using Win32com. I am able to create a daily trigger. However, I cannot find a way to create a trigger every 5 seconds or every minute for that matter. Does anybody have any pointers on how to do that?


Solution

  • As said in a comment, if you want to do stuff with this frequency you are better off just having your program run forever and do its own scheduling.

    In a similar fashion to @Barmak Shemirani's answer, but without spawning threads:

    import time
    
    def screenshot():
        # do your screenshot...
    
    interval = 5.
    target_time = time.monotonic() + interval
    while True:
        screenshot()
        delay = target_time - time.monotonic()
        if delay > 0.:
            time.sleep(delay)
        target_time += interval
    

    or, if your screenshot is fast enough and you don't really care about precise timing:

    while True:
        screenshot()
        time.sleep(interval)
    

    If you want this to run from the system startup, you'll have to make it a service, and change the exit condition accordingly.