0

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
user18953
  • 35
  • 6
  • If you have to do something every five seconds you are probably better off just letting your program run always in background and do it yourself, especially if it can be done straight from Python (you'll avoid the process startup overhead). – Matteo Italia Jan 14 '18 at 21:27
  • I want it to run forever including on startup. How can I do that? My code is taking screenshots every 5 seconds – user18953 Jan 14 '18 at 21:32
  • If you want a python script to run as a service (since you want it to run at startup and forever), you should check [this blog post](https://ryrobes.com/python/running-python-scripts-as-a-windows-service/). It's a bit old, but you can surely make it work. Also check [this](https://stackoverflow.com/questions/32404/is-it-possible-to-run-a-python-script-as-a-service-in-windows-if-possible-how) Stackoverflow question. – Daniel F. Jan 15 '18 at 00:50

2 Answers2

1

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.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
0

pywin32 is not required to create schedule or timer. Use the following:

import threading

def screenshot():
    #pywin32 code here
    print ("Test")

def starttimer():
  threading.Timer(1.0, starttimer).start()
  screenshot()

starttimer()

Use pywin32 for taking screenshot etc.

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77