简体   繁体   English

在特定时间运行 python 代码而不使用 cron 作业

[英]run the python code during a specific time without using cron job

I want to run my code for example, everyday one time between 2pm to 3pm which send out an email.例如,我想在每天下午 2 点到 3 点之间运行我的代码,它会发送一个 email。 I dont want to use cron job for this.我不想为此使用 cron 作业。 Is there a way in python to achieve this? python 有没有办法实现这一点?

my code is below我的代码在下面

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()

Use time package of python. python 的使用时间 package。

import time

function fun():
    # Do something
white 1:
    fun()
    time.sleep(86400)

Start this from 2 PM to 3 PM once with nohup python file.py .使用nohup python file.py从下午 2 点到下午 3 点开始一次。

This script will stop once you shutdown your computer.关闭计算机后,此脚本将停止。 You should restart the script once you restart the system at correct time.在正确的时间重新启动系统后,您应该重新启动脚本。

You can also use the schedule package also.您也可以使用时间表 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)

Start this whenever you can.尽可能开始。 It will run at 2 PM only.它将仅在下午 2 点运行。 If you restart the system you need to restart the script also.如果您重新启动系统,您还需要重新启动脚本。

To automate starting of this script whenever you restart your computer, you can use your bash_profile.要在您重新启动计算机时自动启动此脚本,您可以使用 bash_profile。

Use nano ~/.bash_profile or ~/.bashrc whichever you have.使用 nano ~/.bash_profile~/.bashrc ,无论你有什么。 Add a line nohup python/python3 file.py in that and save.在其中添加一行nohup python/python3 file.py并保存。

PS: Use proper logging into a file. PS:使用正确的登录文件。

Edit: As per your requirement.编辑:根据您的要求。

from datetime import datetime

now_LOCAL = datetime.now()
function fun():
    # Do something

if(now_LOCAL.hour > 14 and now_LOCAL.hour <15):
    fun()

you need to raise a flag so that it wont execute second time in between 2PM to 3PM你需要举一个标志,这样它就不会在下午 2 点到 3 点之间第二次执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM