You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python中PyFCM定时推送通知异常,求实现示例

实现PyFCM定时推送的完整解决方案

我帮你搞定定时推送的问题!PyFCM其实内置了定时推送的支持,只需要用到schedule_time参数就可以实现,这个参数接收一个未来的UTC datetime对象,Firebase会在指定时间自动推送消息。下面是针对你代码的修改示例:

第一步:导入必要模块

首先需要导入处理时间的模块,用来计算定时推送的时间:

import datetime

第二步:修改Android推送逻辑

在你的Android推送代码中,添加定时时间的计算,并传入schedule_time参数:

def index(request):
    if (request.POST['type'] == 'android'):
        push_service = FCMNotification(api_key="abc.pem")
        registration_id = request.POST['registration_id']
        message_title = request.POST['message_title']
        message_body = request.POST['message_body']
        
        # 核心:计算定时推送时间,这里设置为1分钟后(UTC时间)
        # 如果要设置60分钟,把minutes=1改成minutes=60即可
        schedule_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=1)
        
        # 添加schedule_time参数实现定时推送
        result = push_service.notify_single_device(
            registration_id=registration_id,
            message_title=message_title,
            message_body=message_body,
            schedule_time=schedule_time
        )
        print(result)
        return HttpResponse("Hello Testing, world. You're at the tesing index.")
    else:
        # iOS推送部分(APNs本身不直接支持定时推送,需额外处理)
        apns = APNs(use_sandbox=True, cert_file='abc.pem', enhanced=True)
        token_hex = request.POST['registration_id']
        messageTitle = request.POST['message_title']
        dict = {'title': request.POST['message_title'], 'body': request.POST['message_body']}
        payload = Payload(alert=dict, sound="default", badge=1)
        
        # 如果iOS需要定时推送,你需要用任务调度工具(如APScheduler/Celery)延迟执行这段推送代码
        # 示例:用time.sleep模拟(仅测试用,生产环境不推荐)
        # time.sleep(60)  # 延迟1分钟
        
        apns.gateway_server.send_notification(token_hex, payload)
        frame = Frame()
        identifier = 1
        expiry = time.time()+3600
        priority = 10
        frame.add_item(request.POST['registration_id'], payload, identifier, expiry, priority)
        return HttpResponse("Hello Testing, world. You're at the tesing index second")

关键注意事项

  • 时区问题:一定要用UTC时间(datetime.utcnow()),避免因服务器时区导致推送时间偏差
  • PyFCM版本:确保你使用的是最新版PyFCM(可以用pip install --upgrade pyfcm更新),旧版本可能没有schedule_time参数
  • 时间有效性schedule_time必须是未来的时间,如果设置为过去的时间,消息会立即推送
  • iOS定时推送:APNs本身不支持直接设置推送时间,需要在服务器端用任务调度工具(比如APScheduler、Celery)来延迟执行推送代码,不要用time.sleep(生产环境会阻塞请求)

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

火山引擎 最新活动