• 欢迎访问极客猴，分享 Python 入门，网络爬虫，数据分析，赚钱思维相关的技术与思维`QQ群`
• 本站点文章首发于微信公众号【极客猴】，欢迎关注，第一时间接受文章推送~
• 如果您觉得本站非常有看点，那么赶紧使用 Ctrl+D 收藏极客猴吧

# Python 定时任务(上)

3年前 (2017-12-05) 13次浏览

## 1.

``````from datetime import datetime
import time

'''

'''
while True:
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(10)

if __name__ == '__main__':

## 2.

``````from datetime import datetime
import time

'''

'''
'''
第一个参数: 延迟多长时间执行任务(单位: 秒)
第二个参数: 要执行的任务, 即函数
第三个参数: 调用函数的参数(tuple)
'''

# 定时任务
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

if __name__ == '__main__':
while True:
print(time.time())
time.sleep(5)``````

``````1512486945.1196375
1512486950.119873
2017-12-05 23:15:50
1512486955.133385``````

## 3.

`sched`库使用起来也是非常简单。

1）首先构造一个`sched.scheduler`

2）添加调度任务

`scheduler` 提供了两个添加调度任务的函数:

• `enter(delay, priority, action, argument=(), kwargs={})`

• `scheduler.enterabs(time, priority, action, argument=(), kwargs={})`

3）把任务运行起来

``````from datetime import datetime
import sched
import time

'''

'''
# 初始化 sched 模块的 scheduler 类
scheduler = sched.scheduler(time.time, time.sleep)
# 增加调度任务
# 运行任务
scheduler.run()

# 定时任务
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

if __name__ == '__main__':
{"ft_lang_label":"__label__zh","ft_lang_prob":0.83083135,"math_prob":0.8373032,"size":2140,"snap":"2020-45-2020-50","text_gpt3_token_len":1158,"char_repetition_ratio":0.13389513,"word_repetition_ratio":0.16666667,"special_character_ratio":0.2869159,"punctuation_ratio":0.18207283,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9675618,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,9,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-11-29T19:46:27Z\",\"WARC-Record-ID\":\"<urn:uuid:7ae3960e-5840-47fd-9c5b-62a103fbe310>\",\"Content-Length\":\"45587\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:6bc19833-c471-4525-8eaf-18f0b25120c1>\",\"WARC-Concurrent-To\":\"<urn:uuid:3627de60-3d8e-4dae-82da-76a4dea4f499>\",\"WARC-IP-Address\":\"81.71.139.38\",\"WARC-Target-URI\":\"https://geekmonkey.top/121.html\",\"WARC-Payload-Digest\":\"sha1:T4HPN6MDJTNELEEZEHB2SKOVBF3GIYVK\",\"WARC-Block-Digest\":\"sha1:2KSIQKCJBD4VQ4A6X63ETD5L24DPIRL2\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-50/CC-MAIN-2020-50_segments_1606141202590.44_warc_CC-MAIN-20201129184455-20201129214455-00634.warc.gz\"}"}