Victor
Victor

Reputation: 769

Python to run a piece of code at a defined time every day

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?

Upvotes: 6

Views: 22547

Answers (2)

yogesh deshpande
yogesh deshpande

Reputation: 31

you can make use of crontab linux utility, Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at specified times.

for your question , goto the python file's directory and enter in terminal

crontab -e

then within crontab file you can enter like this , for eecuting at 2.30pm daily

30 14 * * *         python3 your_python_file.py

Upvotes: 0

abdulla-alajmi
abdulla-alajmi

Reputation: 501

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!

Upvotes: 31

Related Questions