[英]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.