我有一個帶有一些計劃任務的 Django 應用程式設定。該應用程式使用 Redis 部署在 Heroku 上。如果在控制臺中同步呼叫該任務,或者當我還運行 redis 和 celery 時在本地呼叫該任務。但是,計劃的作業沒有在 Heroku 上運行。
我的任務:
@shared_task(name="send_emails")
def send_emails():
.....
芹菜.py:
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from celery.schedules import crontab
# set the default Django settings module for the 'celery' program.
# this is also used in manage.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings')
# Get the base REDIS URL, default to redis' default
BASE_REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379')
app = Celery('my_app')
# Using a string here means the worker don't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
app.conf.broker_url = BASE_REDIS_URL
# this allows you to schedule items in the Django admin.
app.conf.beat_scheduler = 'django_celery_beat.schedulers.DatabaseScheduler'
# These are the scheduled jobs
app.conf.beat_schedule = {
'send_emails_crontab': {
'task': 'send_emails',
'schedule': crontab(hour=9, minute=0),
'args': (),
}
}
在 Procfile 中:
worker: celery -A my_app worker --beat -S django -l info
我用heroku ps:scale worker=1 -a my-app. [tasks]我可以在作業人員日志中看到已注冊的任務。但是,計劃任務并未在計劃時間運行。send_emails.delay()在生產控制臺中呼叫確實有效。我如何讓工人保持活力和/或在預定時間運行作業?
我有一個使用命令和 heroku 調度程式的解決方法。只是不確定這是否是最好的方法。
uj5u.com熱心網友回復:
如果您在進行免費演示,您應該知道 heroku 服務器處于休眠狀態,并且如果您的計劃任務在您的服務器處于休眠狀態時到期,它將不會運行。
uj5u.com熱心網友回復:
我和你分享任何想法。
運行控制臺并獲取 Dyno 的日期時間。Dyno 使用美國當地時間。
DynoFree 每 30 分鐘睡眠一次,每月只有 450 小時。
嘗試將 celery 更改為 BackgroundScheduler,您需要添加腳本 clock.py 為:
from myapp import myfunction from datetime import datetime from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.schedulers.blocking import BlockingScheduler from time import monotonic, sleep, ctime import os sched = BlockingScheduler() hour = int(os.environ.get("SEARCH_HOUR")) minutes = int(os.environ.get("SEARCH_MINUTES")) @sched.scheduled_job('cron', day_of_week='mon-sun', hour=hour, minute = minutes) def scheduled_job(): print('This job: Execute myfunction every at ', hour, ':', minutes) #My function myfunction() sched.start(
)
在 Procfile 中:
clock: python clock.py
并運行:
heroku ps:scale clock=1 --app thenameapp
問候。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/460365.html
