In my python program, I would like it to run a piece of code at a pre-defined time every weekday, let say 2pm Mon - Fri.
How may I do it please?
Double-click on the Task Scheduler, and then choose the option to 'Create Basic Task…' Type a name for your task (you can also type a description if needed), and then press Next. For instance, let's name the task as: Run Hello World. Choose to start the task 'Daily' since we wish to run the Python script daily at 6am.
Method 1: Using Time Module We can create a Python script that will be executed at every particular time. We will pass the given interval in the time. sleep() function and make while loop is true. The function will sleep for the given time interval.
You can use perform(_:with:afterDelay:) to run a method after a certain number of seconds have passed, but if you want to run code at a specific time – say at exactly 4pm – then you should use Timer instead.
Use crontab and the task scheduler to automate your scripts and save time. Running a Python script could be as easy as opening your IDE or text editor and clicking the run button; however, if the script has to be executed daily or weekly, you don't want to waste time repeating these steps over and over again.
You can use "schedule" library
to install, on terminal enter:
pip install schedule
here is an example of the code you want:
#!/usr/bin/python
import schedule
import time
def job():
print("I am doing this job!")
schedule.every().monday.at("14:00").do(job)
schedule.every().tuesday.at("14:00").do(job)
schedule.every().wednesday.at("14:00").do(job)
schedule.every().thursday.at("14:00").do(job)
schedule.every().friday.at("14:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)
or you can read the documents to see the other functions Click Here
good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With