【问题标题】:Why the email do not send randomly between 1 and 2 o'clock?为什么邮件不会在 1 点到 2 点之间随机发送?
【发布时间】:2019-08-19 13:40:03
【问题描述】:

这是我的 cron 任务。

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

还有 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 = "xxxx@gmail.com"
    receiver_email = "yyyy@gmail.com"
    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))

我想在 1 点到 2 点之间随机发送电子邮件。 连续6天,我发现邮件中的时间总是01:00:0101:00:02,似乎sleep $(( RANDOM \%59 ))m没有阻止/usr/bin/python3 /root/email.py执行,/usr/bin/python3 /root/email.py在sleep命令完成之前执行。

【问题讨论】:

  • 你的 cron 使用哪个 shell (sh/dash/bash)?
  • 不应该在你的 cron 文件中使用 /bin/sleep 吗?

标签: python bash cron


【解决方案1】:

cron 作业在 /bin/sh 中运行,无论您的登录 shell 是什么;你不能使用像 $RANDOM 这样的 Bash 功能。

一个简单的解决方法是强制使用 Bash:

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

但可以说,将sleep 放在 Python 脚本中会更优雅。

【讨论】:

    【解决方案2】:

    你可以说:

    time.sleep( random.randint(1, 3600 ))
    

    在你的脚本中,避免与 shell 打交道。

    【讨论】:

      猜你喜欢
      • 2014-09-22
      • 1970-01-01
      • 2011-07-07
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多