沒有標誌在課堂上有效。 Django在兩個獨立的進程上運行兩次。兩個獨立進程上的類級變量彼此不可見。在這個代碼中使用一個來自數據庫表的標誌(SchedulerUtils是我用go()方法編寫的一個類,它啓動了一個背景apscheduler調度器,該模型在表scheduler_schedulerinfo中使用了一行,所以你必須在這之前插入這一行: 「INSERT INTO scheduler_schedulerinfo(啓動)的值(0);」):
################################## APPS.PY
import os
from django.apps import AppConfig
from apscheduler.schedulers.background import BlockingScheduler, BackgroundScheduler
from scheduler.utils import SchedulerUtils
class SchedulerConfig(AppConfig):
name = 'scheduler'
def ready(self):
startScheduler = True
pid = os.getpid()
#check i'm on heroku
if (os.environ.get("DYNO")):
# i'm on heroku, here runs twice
print("[%s] DYNO ENV exists, i'm on heroku" % pid)
from scheduler.models import SchedulerInfo
schedInfo = SchedulerInfo.objects.all().first()
if (schedInfo.started == 0):
print("[%s] Scheduler not started, starting.... " % pid)
startScheduler = True
# set flag to 1
SchedulerInfo.objects.all().update(started = 1)
else:
print("[%s] Scheduler already running, not starting." % pid)
startScheduler = False # already running
# reset to 0 for next time
SchedulerInfo.objects.all().update(started = 0)
# PRINT FLAG VALUE
from scheduler.models import SchedulerInfo
schedInfo = SchedulerInfo.objects.all().first()
print("[%s] Value of flag schedulerinfo.started: %d" % (pid, schedInfo.started))
if (startScheduler):
su = SchedulerUtils()
su.go()
##################################### MODELS.PY
from django.db import models
class SchedulerInfo(models.Model):
started = models.IntegerField(default=0)
有同樣的問題。你解決了嗎? –
@PavelBernshtam,如果我沒有記錯,它是運行多線程的gunicorn。當我更換服務員託管時,問題就消失了。我甚至沒有包含'run_already = False','並且不包含self.run_already'代碼。 – dmcmulle