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

2

6

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?

Pastille answered 28/4, 2017 at 0:53 Comment(4)
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?Oystercatcher
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.Colchicine
If you are running on a windows machine then see this answer #133471 for an alternative for linux cronetabBarnstorm
Does this answer your question? Python script to do something at the same time every dayBroncho
S
31

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!

Surprising answered 28/4, 2017 at 1:4 Comment(4)
@Pastille you are welcome, please mark it as correct answer ( because I already have projects using it LOL )Surprising
will it behave like a cron? How can I deploy this?Bolzano
is possible to implemented with something more Cron style? to not leaving the while true and the script activeAsben
Is this solution, under the condition that the computer is onCubicle
P
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
Proximate answered 13/5, 2021 at 3:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.