Python 定時任務Timer

2021-10-06 04:37:14 字數 1612 閱讀 5046

ftp檔案傳輸

1、每隔一段時間執行某個功能

timer類建構函式

timer(interval, function, args=, kwargs={}) 

interval: 指定的間隔時間 ,單位:秒

function: 要執行的方法

args/kwargs: 方法的引數

from threading import timer

deffunc

(name)

:#每10s執行一次

print

('hello '

+ name)

t = timer(

10, printtime,

(name,))

t.start(

)if __name__ ==

"__main__"

: func(

'程式設計師'

)

2、一段時間之後執行某個功能
比如,第二天凌晨2點執行該功能

from threading import timer

import datetime

deffunc

(name)

:print

('hello '

+ name)

if __name__ ==

"__main__"

:# 定時

# 獲取現在時間

now_time = datetime.datetime.now(

)# 獲取明天時間

#timedelta(weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0, )

next_time = now_time + datetime.timedelta(seconds =+1

) next_year = next_time.date(

).year

next_month = next_time.date(

).month

next_day = next_time.date(

).day

# 獲取明天凌晨2點時間

next_time = datetime.datetime.strptime(

str(next_year)

+"-"

+str

(next_month)

+"-"

+str

(next_day)

+" 17:09:00"

,"%y-%m-%d %h:%m:%s"

)# 獲取距離明天凌晨2點時間,單位為秒

timer_interval =

(next_time - now_time)

.total_seconds(

) t = timer(timer_interval, func,

('程式設計師',)

) t.start(

)

參考:

[1][2]

timer定時任務

override public void timingpushmessage final message message timer.schedule task,message.getpushtime 當時間還沒到的時候,run方法並不執行,一直到約定時間之後才會執行,但是需要呼叫這個方法。publ...

Timer 定時任務

一 指定時間執行 public class testmain public static void main string args catch exception e 二 按指定的間隔周期性地無限迴圈地執行某乙個任務 public class testmain public static void...

python之Timer實現定時任務

前言 在弄爬蟲時有時候需要定時去爬一些東西,而自己又不可能守在那,這可咋整?於是乎,網上一通亂搜,可搜到了python中threading庫中的timer類可以實現定時執行程式,完成定時任務 於是又開始了學海無涯之路 timer的中文意思是 定時器,顧名思義我們可以通過對time的呼叫來完成一些定時...