Python Forum
function call at defined system time? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: function call at defined system time? (/thread-30125.html)



function call at defined system time? - Holon - Oct-06-2020

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?


RE: function call at defined system time? - ndc85430 - Oct-06-2020

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.


RE: function call at defined system time? - Holon - Oct-06-2020

Win 10, 64 bit using Python 3.6


RE: function call at defined system time? - jefsummers - Oct-06-2020

I'd suggest using task scheduler to set a time to run a batch file that contains a command line to run your script.


RE: function call at defined system time? - DeaD_EyE - Oct-06-2020

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-automation-using-task-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)



RE: function call at defined system time? - snippsat - Oct-06-2020

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).