Search code examples
pythonbashcron

Why the email do not send randomly between 1 and 2 o'clock?


Here is my cron task.

0 1 * * *   sleep $(( RANDOM \%59 ))m && /usr/bin/python3  /root/email.py

And the email.py.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import smtplib,ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

jobTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

def Email(time):
    port = 465
    smtp_server = "smtp.gmail.com"
    sender_email = "[email protected]"
    receiver_email = "[email protected]"
    password = "zzzz"
    message = MIMEMultipart("alternative")
    message["Subject"] = "{}".format(result)
    message["From"] = sender_email
    message["To"] = receiver_email
    text = "send email at {}".format(time)
    part = MIMEText(text, "plain")
    message.attach(part)
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string()) 

Email("success at {}".format(jobTime))

I want to send email randomly between 1 and 2 o'clock. In continious 6 day,i found that the time in the email always 01:00:01 or 01:00:02,it seems that sleep $(( RANDOM \%59 ))m have not block the /usr/bin/python3 /root/email.py to execute,/usr/bin/python3 /root/email.py executed before sleep command finished.


Solution

  • cron jobs run in /bin/sh regardless of your login shell; you cannot use Bash features like $RANDOM.

    A simple workaround is to force Bash:

    0 1 * * *   bash -c 'sleep $(( RANDOM \%59 ))m' && /usr/bin/python3  /root/email.py
    

    but arguably, putting the sleep in your Python script would be more elegant.