在 AsyncIOScheduler 中设置时区

Setting timezone in AsyncIOScheduler

我在太平洋时区,我正在创建一个 discord 机器人,以便在美国中部时间早上 8 点发送消息。

import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
from rich import print
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger


load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.members = True


bot = commands.Bot(command_prefix = '!', intents=intents)

# Will become the good morning message
async def gm():
    c = bot.get_channel(channel_id_removed) 
    await c.send("This will be the good morning message.")

@bot.event
async def on_ready():
    for guild in bot.guilds:
        print(
            f'{bot.user} is connected to the following guild:\n'
            f'\t{guild.name} (id: {guild.id})'
        )

    #initializing scheduler for time of day sending
    scheduler = AsyncIOScheduler()
    # Attempts to set the timezone
    # scheduler = AsyncIOScheduler(timezone='America/Chicago')
    # scheduler = AsyncIOScheduler({'apscheduler.timezone': 'America/Chicago'})
    # scheduler.configure(timezone='America/Chicago')

    # Set the time for sending
    scheduler.add_job(gm, CronTrigger(hour="6", minute="0", second="0")) 

    #starting the scheduler
    scheduler.start()


@bot.event
async def on_member_join(member):
    general_channel = None
    guild_joined = member.guild
    print(guild_joined)
    general_channel = discord.utils.get(guild_joined.channels, name='general')

    print(f'General Channel ID: {general_channel}')
    if general_channel:
        embed=discord.Embed(title="Welcome!",description=f"Welcome to The Dungeon {member.mention}!!")
        await general_channel.send(embed=embed)

bot.run(TOKEN)

环境:

Windows 10
Python 3.10.4

APScheduler           3.9.1
pytz                  2022.1
pytz-deprecation-shim 0.1.0.post0
tzdata                2022.1
tzlocal               4.2

我只是想知道我是否做错了什么?或者如果我想做的事情根本不受支持?如果我使用我的当地时间,它就可以工作,所以我知道这个功能没问题。

您正在使用 asyncio 调度程序,但没有 运行ning asyncio 事件循环,因此这不可能起作用。 Copy/paste 来自 provided example:

from datetime import datetime
import asyncio
import os

from apscheduler.schedulers.asyncio import AsyncIOScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = AsyncIOScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    # Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
    try:
        asyncio.get_event_loop().run_forever()
    except (KeyboardInterrupt, SystemExit):
        pass

它不起作用的原因是,虽然 scheduler.start() 将事件循环实例化为副作用,但它希望循环在其他地方 运行 以便调度程序可以完成它的工作。