You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置服务器代码定时执行?datetime模块使用问题求助

问题分析

你的代码存在两个核心问题:

  1. 时间值固定不变:current_time只在程序启动时获取一次,之后不会实时更新当前时间,只有程序启动瞬间刚好是20:27:30才会执行打印逻辑,后续永远不会触发。
  2. 无持续检查逻辑:autopost函数仅做了单次时间判断,没有持续运行来定时检查,且异步函数未被调度执行。
修复方案

以下提供两种实用的实现方式:

方式一:循环+异步休眠(适合简单场景)

import datetime
import asyncio

async def autopost():
    while True:
        # 每次循环实时获取当前UTC时间
        current_time = datetime.datetime.utcnow().time()
        if current_time.strftime('%H:%M:%S') == '20:27:30':
            print(current_time.strftime('%H:%M:%S'))
            # 避免同一秒内重复触发,休眠1秒
            await asyncio.sleep(1)
        # 每秒检查一次,可根据需求调整间隔
        await asyncio.sleep(1)

# 启动异步任务
asyncio.run(autopost())

方式二:精准定时调度(减少无效检查)

通过计算当前时间到目标时间的间隔,直接休眠到目标时刻,避免频繁循环检查:

import datetime
import asyncio

async def autopost():
    target_time = datetime.time(20, 27, 30)
    while True:
        now = datetime.datetime.utcnow()
        # 构造当天的目标时间点
        target_datetime = datetime.datetime.combine(now.date(), target_time)
        # 如果当前时间已过当天目标点,将目标时间设为次日同一时刻
        if now > target_datetime:
            target_datetime += datetime.timedelta(days=1)
        # 计算需要休眠的秒数
        sleep_seconds = (target_datetime - now).total_seconds()
        await asyncio.sleep(sleep_seconds)
        print(datetime.datetime.utcnow().strftime('%H:%M:%S'))

asyncio.run(autopost())
额外提示
  • 服务器部署时,建议搭配进程管理工具(如systemd、pm2),保证程序后台持续运行。
  • 若只是简单的定时执行需求,直接使用系统自带的crontab(Linux)或任务计划程序(Windows)定时触发脚本,这种方式更稳定可靠。

内容的提问来源于stack exchange,提问作者user22702657

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 00:02:11