如何管理基于Django的站点的任务停止或重新启动? [英] How to manage a stop or restart of a task from Django-based site?

查看:71
本文介绍了如何管理基于Django的站点的任务停止或重新启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在服务器中运行脚本,该脚本将在数据库中自动创建模型实例.这个想法是使用无限循环(例如,在True时),它将无限创建实例,直到我以某种方式停止它为止.我想使用Django从我的网站很好地检查我的数据库有多大,然后从那里停止或重新启动它.这里有什么好的方法?我当时在考虑芹菜,但是我不知道该如何阻止它,这看起来像是一种过大的杀伤力.有什么建议吗?

I'll be running a script in a server which will automatically create model instances in a database. The idea is to use a infinite loop (e.g while True:) which will be endlessly creating instances until I somehow stop it. I want to use Django to nicely check from my website how big my database is, and from there I want to stop or restart it. What could be a good approach here? I was thinking about Celery, but I don't know how would I don't have clear how to stop it and it kind of looks like an overkill. Any suggestion?

推荐答案

一个简单的解决方案是拥有一个类,该类将脚本的名称以及是否应继续运行保存到db:

A simple solution is to have a class that saves to the db the name of the script and whether it should keep running:

class ScriptTracker():
    name = models.Charfield()
    keep_running = models.BooleanField()

然后您的脚本将仅在每个循环中检查db,以查看是否应该停止:

Then your script would just check the db every loop to see if it should stop:

def my_script():

    while True:

        if not ScriptTracker.objects.get(name="my_script").keep_running:
            # stop running
            return

        # creating an instance in the db
        MyObject.objects.create(name="helloworld")
        

  1. 创建ScriptTracker对象

ScriptTracker.objects.create(name ='my_script',keep_running = True)

  1. 开始运行脚本,如果脚本是作为管理命令构建的,则可以很简单地完成该操作:

python manage.py my_script

这篇关于如何管理基于Django的站点的任务停止或重新启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆