sergzach
sergzach

Reputation: 6754

Threads with Django App. Server: Without CRON or Other External Service

I would like to use a thread that starts inside of a Django application.

If we use a standart Python thread it could be stopped by a webserver when the request is finished.

Is there a standard way to do this? Or is there a Django library available that provides this functionality?

Upvotes: 0

Views: 203

Answers (1)

dani herrera
dani herrera

Reputation: 51645

I use threads intensively for long processes. A better solution is Celery, of course.

To define thread:

from threading import Thread

class afegeixThread(Thread):

    def __init__ (self,usuari, expandir=None, alumnes=None, 
                  impartir=None, matmulla = False):
        Thread.__init__(self)
        self.expandir = expandir 
        self.alumnes = alumnes
        self.impartir = impartir
        self.flagPrimerDiaFet = False
        self.usuari = usuari
        self.matmulla = matmulla

    def run(self):        
        errors = []
        try:
           ...
           self.flagPrimerDiaFet = ...
           ...

    def firstDayDone(self):
        return self.flagPrimerDiaFet

Calling thread:

    from presencia.afegeixTreuAlumnesLlista import afegeixThread
    afegeix=afegeixThread(expandir = expandir, alumnes=alumnes, 
                          impartir=impartir, usuari = user, matmulla = matmulla)
    afegeix.start()

    #Waiting for first day done before return html:
    import time
    while afegeix and not afegeix.firstDayDone(): time.sleep(  0.5 )

    #return html code
    return HttpResponseRedirect('/presencia/passaLlista/%s/'% pk )

Upvotes: 1

Related Questions