线程:重新启动线程

时间:2021-06-08 08:44:10

标签: python django multithreading

我有一个 django 项目,目前正在开发中。当用户使用按钮请求更新数据库时,我有几个线程用于通过 API 请求填充数据库。这很好用。

我的问题是我希望用户能够在服务器处于活动状态时多次刷新数据库(将来)。由于线程一旦完成就无法重新启动,我不确定如何继续实现我想要的。这是我的主题:

agencies_thread = threading.Thread(target=fill_agencies, name="Database Updater1")
companies_thread = threading.Thread(target=fill_companies, name="Database Updater2")
contracts_thread = threading.Thread(target=fill_contracts, name="Database Updater3")
orders_thread = threading.Thread(target=fill_orders, name="Database Updater4")
projects_thread = threading.Thread(target=fill_projects, name="Database Updater5")
resources_thread = threading.Thread(target=fill_resources, name="Database Updater6")

我认为每次有人按下按钮时都必须重新创建线程,但是考虑到我的功能,在管理数据库加载的 views.py 函数中添加这些行 ^^ 无法真正工作:

elif urlRequest[:12] == 'loading.html':    # PAGE DE CHARGEMENT
    global updateValue
    if updateValue == 0:
        agencies_thread.start()
        companies_thread.start()
        contracts_thread.start()
        orders_thread.start()
        projects_thread.start()
        resources_thread.start()
        updateValue = 1
    updateState = 0
    if agencies_thread.is_alive():
        agenciesState = 'en cours de chargement'
    else:
        agenciesState = 'Chargement terminé'
        updateState += 1
    if companies_thread.is_alive():
        companiesState = 'en cours de chargement'
    else:
        companiesState = 'Chargement terminé'
        updateState += 1
    if contracts_thread.is_alive():
        contractsState = 'en cours de chargement'
    else:
        contractsState = 'Chargement terminé'
        updateState += 1
    if orders_thread.is_alive():
        ordersState = 'en cours de chargement'
    else:
        ordersState = 'Chargement terminé'
        updateState += 1
    if projects_thread.is_alive():
        projectsState = 'en cours de chargement'
    else:
        projectsState = 'Chargement terminé'
        updateState += 1
    if resources_thread.is_alive():
        resourcesState = 'en cours de chargement'
    else:
        resourcesState = 'Chargement terminé'
        updateState += 1
    if updateState == 6:
        updateValue = 0
        context['updateState'] = 'Base de données mise à jour.'
        html_template = loader.get_template('index.html')
        return HttpResponse(html_template.render(context, request))
    else:
        context['agenciesState'] = agenciesState
        context['companiesState'] = companiesState
        context['contractsState'] = contractsState
        context['ordersState'] = ordersState
        context['projectsState'] = projectsState
        context['resourcesState'] = resourcesState
        html_template = loader.get_template('loading.html')
        return HttpResponse(html_template.render(context, request))

我在想,也许我需要一个带有 updateState 条件的全局变量(如 ìf)来重新创建线程。 你怎么看?

1 个答案:

答案 0 :(得分:0)

添加全局变量“线程状态”并使用它来重新创建函数内的线程。我只需要在函数开始时将线程声明为全局变量,否则我会得到一个错误。