4

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?

Prune
  • 72,213
  • 14
  • 48
  • 72
Victor
  • 419
  • 2
  • 5
  • 14
  • 3
    you want you python script to run 24/7 and execute specific tasks at specific times? why not have specialized scripts and use `crontab` (assuming you are on linux) or `Taskschd.msc` on windows? – Nullman Apr 28 '17 at 00:54
  • This depends on your operating system. You'll likely want to use the `os` and `sys` packages to invoke the scheduling tool provided by your OS. – Prune Apr 28 '17 at 00:57
  • If you are running on a windows machine then see this answer http://stackoverflow.com/questions/132971/what-is-the-windows-version-of-cron for an alternative for linux cronetab – eli-bd Apr 28 '17 at 01:00
  • Does this answer your question? [Python script to do something at the same time every day](https://stackoverflow.com/questions/15088037/python-script-to-do-something-at-the-same-time-every-day) – Gino Mempin Dec 09 '20 at 10:45

2 Answers2

23

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!

abdulla-alajmi
  • 381
  • 1
  • 7
  • 17
0

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