[英]Python script elicits error when run in cron job but at no other time
[英]run the python code during a specific time without using cron job
例如,我想在每天下午 2 点到 3 点之间运行我的代码,它会发送一个 email。 我不想为此使用 cron 作业。 python 有没有办法实现这一点?
我的代码在下面
me=abc@gmail.com
you=bba@gmail.com
msg= MIMEMultipart('alternative')
msg['subject'] = "test email"
msg['from'] = me
msg['to'] = you
text= "happy birthday"
html = '''\
<html>
<body>
<p> hi,</p>
<p> it's your birthday</p>
</body></html>
'''
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
s= smtplib.SMTP("hostname", port=1234)
s.sendemail(me, you, msg.as_string())
s.quit()
python 的使用时间 package。
import time
function fun():
# Do something
white 1:
fun()
time.sleep(86400)
使用nohup python file.py
从下午 2 点到下午 3 点开始一次。
关闭计算机后,此脚本将停止。 在正确的时间重新启动系统后,您应该重新启动脚本。
您也可以使用时间表 package。
import time
import schedule
function fun():
# Do something
schedule.every().day.at("14:00").do(fun)
white 1:
schedule.run_pending()
time.sleep(1)
尽可能开始。 它将仅在下午 2 点运行。 如果您重新启动系统,您还需要重新启动脚本。
要在您重新启动计算机时自动启动此脚本,您可以使用 bash_profile。
使用 nano ~/.bash_profile
或~/.bashrc
,无论你有什么。 在其中添加一行nohup python/python3 file.py
并保存。
PS:使用正确的登录文件。
编辑:根据您的要求。
from datetime import datetime
now_LOCAL = datetime.now()
function fun():
# Do something
if(now_LOCAL.hour > 14 and now_LOCAL.hour <15):
fun()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.