Scheduling multiple schedules - python

I would like to start my code at the start of every hour I have tried using the minutes function of schedule however, the start time of the next process is dependent upon the end of the previous process and with the code I am trying to process the delay accumulates pretty quickly hence, I am trying this method instead. All help is appreciated. Thanks.
The code:
import schedule
import time
schedule.every().day.at("00:00").do(consolidated)
schedule.every().day.at("01:00").do(consolidated)
schedule.every().day.at("02:00").do(consolidated)
schedule.every().day.at("03:00").do(consolidated)
schedule.every().day.at("04:00").do(consolidated)
schedule.every().day.at("05:00").do(consolidated)
schedule.every().day.at("06:00").do(consolidated)
schedule.every().day.at("07:00").do(consolidated)
schedule.every().day.at("08:34").do(consolidated)
schedule.every().day.at("09:00").do(consolidated)
schedule.every().day.at("10:00").do(consolidated)
schedule.every().day.at("11:00").do(consolidated)
schedule.every().day.at("12:00").do(consolidated)
schedule.every().day.at("13:00").do(consolidated)
schedule.every().day.at("14:00").do(consolidated)
schedule.every().day.at("15:00").do(consolidated)
schedule.every().day.at("16:00").do(consolidated)
schedule.every().day.at("17:00").do(consolidated)
schedule.every().day.at("18:00").do(consolidated)
schedule.every().day.at("19:00").do(consolidated)
schedule.every().day.at("20:00").do(consolidated)
schedule.every().day.at("21:00").do(consolidated)
schedule.every().day.at("22:00").do(consolidated)
schedule.every().day.at("23:00").do(consolidated)
while True:
schedule.run_pending()
time.sleep(1)

The schedule package has an option for doing a task every hour:
import schedule
import time
schedule.every().hour.do(consolidated)
while True:
schedule.run_pending()
time.sleep(1)

Related

How do I activate a python program at exact whole hours? (12:00:00pm, 04:00:00am)

I want to write a program that keeps running in the background and performs a certain task at each hour of the day. How do I achieve this?
for production i would add cron or schedule
# Schedule Library imported
import schedule
import time
# Functions setup
def sudo_placement():
print("Get ready for Sudo Placement at Geeksforgeeks")
def good_luck():
print("Good Luck for Test")
def work():
print("Study and work hard")
def bedtime():
print("It is bed time go rest")
def geeks():
print("Shaurya says Geeksforgeeks")
# Task scheduling
# After every 10mins geeks() is called.
schedule.every(10).minutes.do(geeks)
# After every hour geeks() is called.
schedule.every().hour.do(geeks)
# Every day at 12am or 00:00 time bedtime() is called.
schedule.every().day.at("00:00").do(bedtime)
# After every 5 to 10mins in between run work()
schedule.every(5).to(10).minutes.do(work)
# Every monday good_luck() is called
schedule.every().monday.do(good_luck)
# Every tuesday at 18:00 sudo_placement() is called
schedule.every().tuesday.at("18:00").do(sudo_placement)
# Loop so that the scheduling task
# keeps on running all time.
while True:
# Checks whether a scheduled task
# is pending to run or not
schedule.run_pending()
time.sleep(1)
You can write a if condition in a infinite while loop to check if current time is equals to your time say (12:00:00pm, 04:00:00am) or you can make use of the sleep method, it stops the exexution of your code for the specified amount of time, you must find that by calculating the difference between your time and the current time and this method does not consume much memory and cpu cycles like the previous method.
I'd advise setting up a cron job to run your python program at specific time
Try this:
from datetime import datetime # Import datetime
def schedule(time, function): # Syntax:
cur_time = datetime.strftime("%T") # time: 24 hour time hh:mm:ss (09:00:00 or 21:00:00)
if cur_time == time: # function: lampda: to_execute()
function()
def scheduled_function():
print("TEST")
while True:
schedule("15:00:00", lampda:scheduled_function()) # Schedule scheduled_function() to execute at 3:00 pm

Running Python schedule daily at random times

How do I run a scheduled job at random times daily starting with today? I want to use the schedule package.
pip install schedule
import schedule
def job()
print("foo")
return schedule.CancelJob
while True:
time_str = '{:02d}:{:02d}'.format(random.randint(6, 10), random.randint(0, 59))
print("Scheduled for {}".format(time_str))
schedule.every().day.at(time_str).do(job)
schedule.run_pending()
The above code just spins:
Scheduled for 06:36
Scheduled for 10:00
Scheduled for 06:18
You're providing a moving target by putting your random time generator inside you while loop. Specifically, after reviewing the source code here, it is clear that the job will only run if datetime.datetime.now() >= self.next_run is true (see scheduler.run_pending() and job.should_run() definitions). Because you are always moving job.next_run, you will only hit it if it happens to be in the past on that particular iteration of the loop. Interestingly, I think this would cause a bug where the probability of actually running your job increases as you approach 24:00, though this has yet to be shown. I think you need to create a separate function for generating the next random time, and call it from your job function. For example:
import schedule
import time
import random
def job():
print("foo")
schedule_next_run()
return schedule.CancelJob
def schedule_next_run():
time_str = '{:02d}:{:02d}'.format(random.randint(6, 10), random.randint(0, 59))
schedule.clear()
print("Scheduled for {}".format(time_str))
schedule.every().day.at(time_str).do(job)
schedule_next_run()
while True:
schedule.run_pending()
time.sleep(60)
Note that the example may not be random for the day that the job starts, as your random time may be before the time you happen to start your script. You could work in a way to pick a random time in the future on the first day to circumvent this as needed.
To verify the above example, I used shorter time spans. The following works for me:
import schedule
import time
import random
def job():
print("foo")
schedule_next_run()
return schedule.CancelJob
def schedule_next_run():
time_span = random.randint(1, 5)
schedule.clear()
print(f'Scheduled in {time_span} seconds')
schedule.every(time_span).seconds.do(job)
schedule_next_run()
while True:
schedule.run_pending()

Schedule a job to run every 5 mins only on a particular day in python

I want to run a cron job for every 5 mins only on a particular day of the week. I am using python schedule library and I can do these jobs individually. But how do I club them?
code
import schedule
def check():
print('Checking')
schedule.every(10).monday.do(check)
while True:
# Checks whether a scheduled task is pending to run or not
schedule.run_pending()
This gives an error IntervalError: Use mondays instead of monday when I try with mondays, I get an error AttributeError: 'Job' object has no attribute 'mondays' can someone help me with this.
I don't think the schedule package supports combinations of different time units the way you want. You can achieve what you want doing something like:
import schedule
import time
import datetime
def job():
if datetime.datetime.today().weekday() == 0:
print("I'm working...")
schedule.every(5).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
Maybe not the most elegant solution, though.
Did you try with "time"?
import time
...
schedule.every().monday.do(job)
while True:
schedule.run_pending()
time.sleep(300)

Scheduling task to run every n seconds, starting at a specific time

When using the schedule package in Python, I would like to schedule a task to start at a specific time, and then run every 10 seconds. I was able to get the task to run every 10 seconds, using schedule.every(10).seconds.do(x) and I also got it to run at a set time, using schedule.every().day.at('13:25').do(x). But how would I put these together? I tried to combine them into the following, but I got RecursionError: maximum recursion depth exceeded
import schedule
import time
def test():
print('Hello, World!')
def sched_job():
schedule.every(10).seconds.do(test)
while True:
schedule.run_pending()
time.sleep(1)
schedule.every().day.at('13:56').do(sched_job)
while True:
schedule.run_pending()
time.sleep(1)
sched_job()
Don't call run_pending() from inside your job, just schedule an additional job and use your main loop to call it. The only thing you need to change in your code is removing the while True block in sched_job(). Also, in order to prevent a second schedule to be created every 10 seconds on the next day at the given time, the outer job should immediately cancel itself once it is executed once. You can do this by returning schedule.CancelJob.
Here is the modified code:
import schedule
import time
def test():
print('Hello, World!')
def sched_job():
schedule.every(10).seconds.do(test)
return schedule.CancelJob
schedule.every().day.at('13:56').do(sched_job)
while True:
schedule.run_pending()
time.sleep(1)

python How to loop a function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the best way to repeatedly execute a function every x seconds in Python?
Hi so here is the code I have:
client = myclient(info1,info2)
sellor()
Contractor()
It works perfectly but what I would like to do is to make python launch that code every 60 seconds indefinitely...
I don't actually understand how I have to put the code together with the time loop
Any help is appreciated
Thank's
If the 60 seconds ignores the time it takes to execute your code):
from time import sleep
while True:
sleep(60)
# your code here
but if the 60 seconds takes into account the time it takes to execute your code:
from time import sleep
from os import fork
while True:
sleep(60)
fork() # create child process
# your code here
Use the sleep method. Just create a loop (while, for, whatever) and sleep for 60 secs every iteration.
import time
while True:
client = myclient(info1,info2)
sellor()
Contractor()
time.sleep(10)
hope it works,all the best mate
import time
repeat_time = 3.0
while True:
start_time = time.time()
# Your code goes here
time.sleep(max(repeat_time - (time.time() - start_time), 0.0))
And your code will be executed exactly every "repeat_time"
You could use sleep as already mentioned. But because there may be a variable amount of time needed for your own functions to run, this wouldn't necessarily mean your functions are run every 60 seconds.
If it was important that the period between each start of your functions is closer to 60 seconds, you could use time. I haven't tried this but something like
import time
while True:
# Get the current time
startTime = time.time()
# Your functions
client = myclient(info1,info2)
sellor()
Contractor()
delay = True
while delay:
if time.time() - startTime > 60:
delay = False # Break the delay
You might also think of just scheduling the task through windows scheduler. The benefit here would end the script once run and then execute the script again after scheduled interval. In the second approach it seems that the script instance process would continually run and only use the sleep function to do nothing for the specified time. I take it this way if the scripts fails at any instance you might have to keep a check to restart the script. While as a scheduled activity the script will be executed in any case at that specified intervals.
You might also not want the process thread to be kept running for the python script executed. I will research on this and you might get to hear form our other folks in the mean while.
Regards,
Harshal

Categories

Resources