I want to execute two functions every minute. After 1.5 seconds Dowork1() and Dowork2() also after 31 seconds execute Dowork2(). Following code is working but it is delaying and blocking other threads as this is continuous while loop. i have thought of using sleep two time but it will be messy and difficult to calculate exact time of sleep. Please let me know what is best way to do this.
dateTimeObj = datetime.now()
minute = dateTimeObj.minute
hour = dateTimeObj.hour
firstExecuteseconds = 1.5
secondExecuteseconds = 31.0
while True:
if hour < datetime.now().hour:
hour = datetime.now().hour
minute = datetime.now().minute - 1
if minute < datetime.now().minute:
isFirstExecuted = False
isSecondExecuted = False
if datetime.now().second > firstExecuteseconds and isFirstExecuted == False:
DoWork1()
DoWork2()
isFirstExecuted = True
if datetime.now().second > secondExecuteseconds and isSecondExecuted == False:
DoWork2()
isSecondExecuted = True
if isFirstExecuted and isSecondExecuted:
hour = datetime.now().hour
minute = datetime.now().minute
6
If you want to run a function every one minute without blocking other threads, you can do:
import threading
import time
def my_task():
print("Task executed at:", time.ctime())
def execute_task_every_minute():
while True:
my_task()
time.sleep(60) # Wait for 60 seconds before running again
# Create a thread to run the function
thread = threading.Thread(target=execute_task_every_minute)
# Start the thread
thread.start()
So you should make two threads for your functions and do sleeping in those threads which doesn’t block your main thread.
You can also calculate the execution time of you operation and sleep the remaining time to be exact.
1
I think using the asyncio library makes sense since you are writing concurrent processes.
import asyncio
async def task1():
await asyncio.sleep(1.5)
print("task1()")
async def task2():
await asyncio.sleep(31)
print("task2()")
async def background_task():
print("Long background task...")
await asyncio.sleep(600)
print("...done")
async def schedule_tasks():
while True:
start_time = asyncio.get_running_loop().time()
task1_coroutine = asyncio.create_task(task1())
task2_coroutine = asyncio.create_task(task2())
elapsed_time = asyncio.get_running_loop().time() - start_time
if elapsed_time < 60:
await asyncio.sleep(60 - elapsed_time)
async def main():
asyncio.create_task(background_task())
await schedule_tasks()
if __name__ == "__main__":
asyncio.run(main())
Does having multiple synchronous python programs interacting make sense? You might want to learn about cron for starting programs on a schedule in Mac and Linux, or Windows Task Scheduler. Then you need to figure out how to do interprocess communication safely.
One way to do this is to separate the scheduler (your while loop) from the actual work being performed. Instead of performing the functions directly in the while loop, you can spawn new threads for each execution. This frees up the scheduler to continue checking the time and launch new threads with a good degree of precision and not have its timing impacted by waiting for tasks (your functions) to complete.
In a simplified example:
while True:
if is_time_to_execute_task_1():
task_thread = threading.Thread(target=DoWork1)
task_thread.start()
if is_time_to_execute_task_2():
task_thread = threading.Thread(target=DoWork2)
task_thread.start()
time.sleep(0.01) # or whatever resolution you need