Cron can be useful.
crontab
file where each line specifies times and commands
crontab
file (in addition to system crontabs)
# For details see man 4 crontabs # Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * command to be executed
Here's an example (/etc/crontab
):
07 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 1 * * fri root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly # ================================================================ # backup strategy is all on old-tempest # these files will always have new contents and so should be backed up afresh each day 1 0 * * * root date >| /home/sysadmin/today; date >| /students/gdome/today # end of the day, check the backups 30 23 * * * root /root/bin/check-backup-logs # on the weekend, check for disk hogs, during the cp-al 0 1 * * 6 root /root/bin/disk-hogs # put this on new because of the python script # this will run while the cp -al is happening 30 1 * * * root /home/sysadmin/bin/find_quiet_homedirs
The crontab files are stored in a special system directory
(typically /var/spool/cron
). The following command to allow
you to edit your crontab in your favorite editor (the value of the EDITOR
environment variable):
$ printenv $ echo $EDITOR $ EDITOR=emacs $ crontab -e
To see your crontab, do
$ crontab -l
We can schedule an email message to get sent every day at a particular time. To do so, we need:
The following bash script sets up your Python program:
#!/bin/bash source /home/cs304/public_html/downloads/venv/bin/activate cd /home/cs304/public_html/downloads/cron/ python plainmail2.py echo "email sent"
To make this executable, do:
$ chmod a+rx plainmail2.sh
The following sends the emails:
# Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.mime.text import MIMEText def email(body, to='scott.anderson@wellesley.edu', from_addr='cs304@wellesley.edu', subject='Subject'): msg = MIMEText(body) msg['Subject']=subject msg['From']=from_addr msg['To']=to # Send the message via our own SMTP server. s = smtplib.SMTP('localhost') s.send_message(msg) s.quit() if __name__ == '__main__': import pymysql import dbi dsn = dbi.read_cnf('/home/cs304/.my.cnf') conn = dbi.connect(dsn) dbi.select_db(conn,'webdb') curs = dbi.dictCursor(conn) curs.execute('select addr from emails') for row in curs.fetchall(): print(row['addr']) email('Just a reminder ...', to=row['addr'], subject='confirmation')
Copy the cron folder and then do this activity.
$ cd ~/cs304 $ cp -r ~cs304/pub/downloads/cron cron $ cd cron
email-table.sh
file to set up your emails.
crontab
file to run the script a few minutes from now