I have an app that does transcription. I want that if the user tries to reload they are alerted that reloading will stop their task from completing. I tried to use it with unload
but it didn’t work most of the time and I know that it is inconsistent. I would like to pause the task if the user tries to reload. They will get the browser warning alert and if they decide that they still want to reload the task will be terminated.
The idea I have is to trigger a beforeunload
which will give them a warning and trigger the pausing of the celery task. I have a polling function on the frontend set up using JS that polls if the task is still running every 5 seconds. If the user reloads this polling function will stop running and so the backend will stop being polled which will trigger the celery task termination.
Otherwise, the function will receive the poll if the user cancels or hasn’t reloaded and the task is unpaused.
Here is my polling function:
function pollTaskStatus(taskId) {
currentTaskId = taskId;
console.log(currentTaskId)
pollInterval = setInterval(() => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status == 200) {
const response = JSON.parse(xhr.responseText);
if (response.status === 'completed') {
console.log('completed');
if (response.reload) {
// Reload the page to load the correct HTML template
window.location.reload();
}
clearInterval(pollInterval); // Stop polling once completed
isTranscribing = false; // Set to false when transcription is complete
}
} else {
showError('An error occurred.');
clearInterval(pollInterval); // Stop polling on error
isTranscribing = false; // Set to false on errors
}
};
xhr.onerror = function() {
showError('Connection error. Please check your network connection and try again.');
clearInterval(pollInterval); // Stop polling on network error
isTranscribing = false; // Set to false on network error
};
xhr.open('GET', `/transcribe/poll_task_status/${taskId}/`, true);
xhr.send();
}, 5000); // Poll every 5 seconds
}
I’m also open to any better ideas for dealing with potential customer reload during a running task. My backend is django and I am running celery[redis].