Using Crontab for Scheduling Task in Python

linux Oct 21, 2019

Crontab is a linux command that shows the list of  commands(jobs) that needs to be automatically scheduled for specific tasks so that the tasks run in a specific time repeatedly or helps to create a scheduled task.

A job scheduler 'cron' is used to execute tasks(jobs) in CronTab. cron is named after a Greek word chronos which means time. cron is the system process that will automatically perform tasks for you according to a set schedule.

Crontab Commands

To list all the jobs

crontab -l
show list of jobs defined which needs to be run on a regular basis.

to edit/create jobs

crontab -e
creates or edit the jobs.

Contab Tasks Format

The format for running a task in a specific schedule is written below.

[Minute] [hour] [Day_of_the_Month] [Month_of_the_Year] [Day_of_the_Week] [command]

NOTE:
* any value
,   value list separator-range of values
/   step values
*/5 * * * * python myemail.py

The above job will run your script every 5 min

* 4,5 * * * 

The above job will run your script at every minute past hour 4 and 5.

 * */1 * * * python myemail.py

The above job will run your script Every Minute past Every 1 hr.

5 0 * 8 * python myemail.py

The above job will run your script At 00:05 in August

Now, Lets try using crontab to email a user everyday sending beautiful quotes.

We will be sending ourselves a quotes everyday at 6.

Here is a python script to send email.

File: myemail.py

#myemail.py

import smtplib

from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import datetime
import wikiquote


def main():
    names = ['YOUR_NAME'] 
    emails  = ['YOUR_EMAIL']
    message_template = read_template('message.txt')

    # set up the SMTP server
    s = smtplib.SMTP(host='smtp.gmail.com', port=587)
    s.starttls()
    s.login('GMAIL_EMAIL', 'GMAIL_PASSWORD')

    # For each contact, send the email:
    for name, email in zip(names, emails):
        msg = MIMEMultipart()       # create a message

        # add in the actual person name to the message template

        message = message_template.substitute(PERSON_NAME=name.title(),    													QUOTE=wikiquote.qotd()[0])

        # Prints out the message body for our sake
        print(message)

        # setup the parameters of the message
        msg['From']=name
        msg['To']=email
        msg['Subject']="This is TEST"
        
        # add in the message body
        msg.attach(MIMEText(message, 'plain'))
        
        # send the message via the server set up earlier.
        s.send_message(msg)
        del msg
        
    # Terminate the SMTP session and close the connection
    s.quit()
    
if __name__ == '__main__':
    main()

File: message.txt

Dear ${PERSON_NAME} ,
QUOTE OF THE DAY: ${QUOTE}
Yours Truly,

type the command : crontab -e

Add the below line to end of the file.

0 6 * * * python directory_location/myemail.py

this will run the myemail.py script everyday at 06:00.

Enjoy!