Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 896
Victor Avatar asked Apr 28 '17 00:04

Victor


People also ask

How do I make a Python script run automatically daily?

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.

How do I run a Python program at a specific time?

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.

How do I run a code at a specific time?

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.

How do you automate a code in Python?

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.


1 Answers

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!

like image 200
abdulla-alajmi Avatar answered Oct 20 '22 19:10

abdulla-alajmi