我在运行定期任务时遇到问题?当我运行代码芹菜工人 -A 任务时 --loglevel=debug。看起来不错,但它在终端中的此消息后停止并且不执行任何操作:[2019-07-10 22:29:21,149:调试/主进程] 基本qos:prefetch_count->16
from celery import Celery
from celery.schedules import crontab
from datetime import date, timedelta
from config import *
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
import smtplib
import ssl
import os
app = Celery('main', broker='redis://localhost')
app.conf.timezone = 'Asia/Bishkek'
@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
sender.add_periodic_task(30.0, send_archives(), expires=10)
@app.task
def send_archives():
yesterday = date.today() - timedelta(days=1)
if len(os.listdir('archives')):
msg = MIMEMultipart()
msg['Subject'] = 'Archives for ' + yesterday.strftime('%d_%m_%Y')
msg['From'] = EMAIL_HOST_USER
msg['To'] = EMAIL_HOST_RECEIVER
for filename in os.listdir('archives'):
with open(os.path.join('archives', filename), 'rb') as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
f"attachment; filename={filename}",
)
msg.attach(part)
os.unlink(os.path.join('archives', filename))
context = ssl.create_default_context()
with smtplib.SMTP_SSL(EMAIL_HOST, EMAIL_PORT, context=context) as server:
server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
server.sendmail(EMAIL_HOST_USER, EMAIL_HOST_RECEIVER, msg.as_string())
问题出在expires=10
中。很容易误解这个参数。它的作用是告诉Celery"如果你无法在10秒内执行这个任务,就不要运行它"(任务"过期"(。
因此,每 30 秒您将任务发送到 Celery 集群。如果任务运行时间超过 30 秒,您的队列将变得满员,之后计划的许多任务将过期。
更糟糕的是 - 如果出于某种原因您的任务达到永久阻塞的条件,则此类任务可能会填满队列,并且不会运行其他任务。