Python Forum

Full Version: function call at defined system time?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone,

I want to create a background service like script, that will execute tasks at given times and/or dates. I would like to use asyncio for that, since I will have a loop going anyway. But I have hard times to find a way to monitor system time and trigger events at a given time.

Any idea how to do that?
It would help to know which operating system you're running, as they tend to have their own ways of doing these sorts of things.
Win 10, 64 bit using Python 3.6
I'd suggest using task scheduler to set a time to run a batch file that contains a command line to run your script.
Here a very naive approach: https://datatofish.com/python-script-windows-scheduler/
Another tutorial (not much different from first one): https://www.jcchouinard.com/python-autom...scheduler/

Instead of using python.exe or a .bat file, you should use py.exe -3.6 your_program.py.
(Python 3.9 was released yesterday)

If your application is not a console application or if you want to hide the console, use instead of py.exe pyw.exe.

For testing it, I've used this code:
import sys
from tkinter import Tk
from tkinter.messagebox import showinfo


root = Tk()
root.withdraw()
showinfo("Hello from Python", sys.version)
There are also libraries that work fine for like schedule, APScheduler, pycron
The two first have i used serval times before,Python job scheduling for humans is maybe the easiest to use.

Holon Wrote:I would like to use asyncio for that
That's maybe overkill for this task,as usually don't need 1000's task to load at same time for this.
Schedule use simpler Threading if that's needed.
import threading
import time
import schedule


def job():
    print(f"I'm running on thread {threading.current_thread()}")

def run_threaded(job_func):
    job_thread = threading.Thread(target=job_func)
    job_thread.start()

schedule.every(10).seconds.do(run_threaded, job)
schedule.every(10).seconds.do(run_threaded, job)
schedule.every(10).seconds.do(run_threaded, job)

while 1:
    schedule.run_pending()
    time.sleep(1)
APScheduler start separate Thread automatic with schedulers.background
apscheduler Wrote:A scheduler that runs in the background using a separate thread (start() will return immediately).