Thanks KenWhitesell.
I tried Celery and it worked somehow fine but only for the first run. I mean, after trigering , the task.py generate a random number once and save it in the file . But I want it to continously generate random numbers and save them in text file. I tried Celery Beat and it looks good but it creates a new task everytime. In the template, result.html, ajax get the task.id and then get the value of that task. In the second run , a new task was created but ajax does not know its id so it failed to show the second value and so on.
The current value of celery_var (from tasks.py) must be displayed always on result.html.
Thank you
#task.py
from celery import shared_task
from time import sleep
import random
@shared_task
def background_task():
# Simulate a long-running task
sleep(1)
celery_var = random.uniform(15.0, 30.0)
with open(‘celery.txt’, ‘a’) as file:
# Write some text to the file
file.write(f’{celery_var}\n’)
return celery_var
#views.py
from .tasks import background_task
def trigger_task(request):
background_task.delay() # This will run the task independently
result = background_task.delay()
return JsonResponse({‘task_id’: result.id}) # Return the task ID in the response
# return JsonResponse({‘status’: ‘Task started’})
def get_task_result(request, task_id):
task_result = AsyncResult(task_id)
print("######### result: ", task_result.ready())
if task_result.ready():
result = task_result.result
return JsonResponse({‘status’: ‘completed’, ‘result’: result})
else:
return JsonResponse({‘status’: ‘pending’})
#result.html
Celery Task Status
$(document).ready(function() {
var taskId = $('#task-id').val(); // Get task ID from hidden input
if (!taskId) {
// If no task ID, start a new task
startTask();
} else {
// If task ID exists, check its status
checkTaskStatus(taskId);
}
function startTask() {
$.ajax({
url: "{% url 'trigger_task' %}", // Trigger the task endpoint
method: 'GET',
success: function(response) {
console.log('Task started. Task ID:', response.task_id);
if (response.task_id) {
$('#task-id').val(response.task_id); // Store task ID
checkTaskStatus(response.task_id); // Start checking task status
} else {
$('#result').text('Failed to retrieve task ID.');
}
},
error: function() {
$('#result').text('Failed to start task.');
}
});
}
function checkTaskStatus(taskId) {
$.ajax({
url: "{% url 'get_task_result' 'dummy_id' %}".replace('dummy_id', taskId),
method: 'GET',
success: function(response) {
console.log('Task status response:', response);
if (response.status === 'completed') {
$('#result').text('Task result: ' + response.result);
} else {
$('#result').text('Task is still processing...');
setTimeout(function() {
checkTaskStatus(taskId); // Poll every 2 seconds
}, 2000);
}
},
error: function() {
$('#result').text('Failed to retrieve task result.');
}
});
}
});
</script>
Celery Task Status
Starting task...
#settings.py
Celery Beat settings
CELERY_BEAT_SCHEDULE = {
‘run-background-task-every-10-seconds’: {
‘task’: ‘lynx.tasks.background_task’,
‘schedule’: 10.0, # Task runs every 10 seconds
},
}
CELERY_TIMEZONE = ‘UTC’