前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Thread 的自定义定时器

使用Thread 的自定义定时器

作者头像
用户2458545
发布2022-09-07 11:41:10
2490
发布2022-09-07 11:41:10
举报
文章被收录于专栏:阿牛的牙

在日常工作中总会有一些定时任务的操作, 定时邮件, 定时短信, 定时脚本任务等等。

常见的操作是使用linux下的crontab操作,或者使用celery的定时任务。

为何不尝试一下新东西呢? 

代码语言:javascript
复制
import time
import sys
import signal
import datetime
import threading


# 定时器
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)

    interval_time = delay_time()
    t = threading.Timer(interval_time, event_func)  # interval_time:定时时间, event_func: 执行的函数
    t.setDaemon(True)
    t.start()


# 取时间点 24小时以后执行
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()


if __name__ == "__main__":
    try:
        signal.signal(signal.SIGINT, quit_sys)
        signal.signal(signal.SIGTERM, quit_sys)
        schedule_update()
        print("schedule_update server starting up...\nHit Ctrl-C to quit.\n")
        while 1:
            time.sleep(1)
    except Exception as e:
        print(e)

links: https://www.linuxidc.com/Linux/2019-09/160795.htm

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年9月30日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
短信
腾讯云短信(Short Message Service,SMS)可为广大企业级用户提供稳定可靠,安全合规的短信触达服务。用户可快速接入,调用 API / SDK 或者通过控制台即可发送,支持发送验证码、通知类短信和营销短信。国内验证短信秒级触达,99%到达率;国际/港澳台短信覆盖全球200+国家/地区,全球多服务站点,稳定可靠。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档