【发布时间】:2019-06-19 10:09:39
【问题描述】:
这是我的第一个线程程序。我在这里面临一个奇怪的问题。我正在构建一个简单的调度程序,如 Django 中的应用程序,其中函数名称(定期执行)将连同它们的下一个执行时间一起存储在 Django 模型中。
执行管理命令启动一个线程,该线程连续运行,检查是否有任何函数的执行到期,如果是,则启动一个新线程来执行该函数。这样,为每个函数创建了单独的线程(至少,这就是想法!)。
class Command(BaseCommand):
def __init__(self):
super(Command, self).__init__()
self.lock = None
def handle(self, *args, **kwargs):
self.lock = threading.RLock()
t1 = threading.Thread(target=self.cron_thread)
t1.start()
t1.join()
def cron_thread(self):
while True:
# Fetch only Active records
scheduled_actions = Scheduler.objects.filter(active=True)
for scheduled_action in scheduled_actions:
# check if execution is due
if scheduled_action.next_execution_time == datetime.now():
# creating a new thread
function_thread = threading.Thread(target=eval(scheduled_action.function_name), args=[self.lock])
function_thread.start()
function_thread.join()
scheduled_action.next_execution_time = local_timezone.localize(datetime.now() + relativedelta(minutes=scheduled_action.interval))
scheduled_action.run_now = False
scheduled_action.save()
def somefunction(self):
self.lock.acquire()
# function body
self.lock.release()
我创建的开始执行整个程序的命令是:python3 manage.py runcrons-debit
执行此命令后,我可以在 htop 结果中看到两个进程正在运行并消耗近 80% 的 CPU,如下图所示:
View Image
请注意这里还没有调度程序记录处于活动状态。
当调度程序记录被激活并且函数实际运行时,htop 中显示的进程增加到三个,CPU 使用率急剧下降到 0.0%。如下图所示:
View Image
这里有两件事我无法理解,
【问题讨论】:
-
您的条件
scheduled_action.next_execution_time == datetime.now()永远是True的可能性非常低(datetime.now()是一个日期时间对象,它包括小时、分钟、秒甚至微秒)。 -
因为
while True: do stuff?使用计算能力?使用 30 秒、1 分钟、10 分钟的睡眠时间,具体取决于您需要的分辨率。更好:使用调度程序并让每个需要它的线程在 x 时间重新启动自己.. 参见 f.e. stackoverflow.com/questions/2398661/…
标签: python django python-3.x python-multithreading django-management-command