I have a main function, where all the tasks are located. The first task I want to run continuous. My second task I want to run on a specific date (For example: Every Monday at 12AM). The last task must rerun the the main function but with other parameters (I want to run this task every hour). I'm using Python on Ubuntu 18.
I've tried to use the module 'schedule' and searched for an answer here on stack overflow, google, ... but I didn't found anything useful.
import schedule, time
def main(par1, par2, par3):
def task1():
# Do something
print("Executing task1")
def task2():
# Do something different
print("Executing task2")
def rerunTask():
print("Reruning main task")
main(1,2,3) # Rerun main function with other parameters
schedule.every().monday.at("12:00").do(task2)
schedule.every(0.5).seconds.do(task1)
schedule.every().hour.do(rerunTask)
main(2,3,1)
When I tried this code everything worked fine until the "rerun task". After he executes this task he continuous reruns this function for the rest of the time.
Can someone please help me?
You could use time library with threading library and based on epochs value, the function will be executed.
Warning: Because of the use of thread, you might have to kill the terminal to exit.
import time, threading
def main(par1, par2, par3):
def task1():
# Do something
print("Executing task1")
def task2():
# Do something different
print("Executing task2")
def run_task1():
while(1):
task1()
time.sleep(0.5)
def run_task2():
while(1):
task2()
time.sleep(3600)
def run_task3():
week_diff = 604800
curr_time = time.time()
first_monday_epoch = 345600
total_monday_crossed = int((curr_time - first_monday_epoch) / week_diff)
next_monday = (total_monday_crossed + 1) * week_diff + first_monday_epoch
time.sleep(next_monday - time.time())
while(1):
task2()
time.sleep(604800) #week time difference
t1 = threading.Thread(target=run_task1, args=())
t2 = threading.Thread(target=run_task2, args=())
t3 = threading.Thread(target=run_task3, args=())
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
main(2,3,1)
Note: I used Epoch converter to calculate epoch of first monday 00:00 AM and other epoch information.