Python timed tasks

Source: Internet
Author: User

Import threading
Import time
Import datetime

Def exec_update ():
Time.sleep (5)

Def event_func ():
Now_time = Datetime.datetime.now (). Strftime ('%y-%m-%d%h:%m:%s ')
Print (Now_time)
Exec_update ()
t = Threading. Timer (1, Event_func)
T.setdaemon (True)
T.start ()

if __name__ = = ' __main__ ':
t = Threading. Timer (0, Event_func)
T.setdaemon (True)
T.start ()
While 1:
Pass

########################################################################################################

"""

Timed tasks, execution at a certain point in time

"""
Import OS
Import time
Import JSON
Import Sys
Import Sched
Import Signal
Import datetime
Import threading
Import subprocess
From subprocess Import Devnull
Import Service.db_conn as Db_conn

#具体任务
Def exec_update ():

Print ("Update ...")


#定时器
Def schedule_update ():
t = Threading. Timer (0, Event_func)
T.setdaemon (True)
T.start ()

#执行函数
Def event_func ():
Now_time = Datetime.datetime.now (). Strftime ('%y-%m-%d%h:%m:%s ')
Print (Now_time)
Exec_update ()
Interval_time = Delay_time ()
t = Threading. Timer (Interval_time, Event_func)
T.setdaemon (True)
T.start ()

#取时间点
Def delay_time ():
# now time
Now_time = Datetime.datetime.now ()
# Tomorrow Time
Next_time = Now_time + Datetime.timedelta (days=+1)
Next_year = Next_time.date (). Year
Next_month = Next_time.date (). Month
Next_day = Next_time.date (). Day
# Get Tomorrow 00:00
Next_time = Datetime.datetime.strptime (str (next_year) + "-" +str (next_month) + "-" +str (next_day) + "00:00:00", "%y-%m-%d %h:%m:%s ")

# get secondes
Delay_time = (next_time-now_time). Total_seconds ()
Return Delay_time

def quit_sys (Signum, frame):
Sys.exit ()

#接收Ctrl +c Signal
if __name__ = = "__main__":
Try
Signal.signal (signal. SIGINT, Quit_sys)
Signal.signal (signal. SIGTERM, Quit_sys)
Schedule_update ()
Print ("Hit Ctrl-c to Quit.\n")
While 1:
Time.sleep (1)
Except Exception as E:
Print (e)

Python timed tasks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.