Base solution for your next web application
Open Closed

Deleting a background job #12149


User avatar
0
uenlkr4e created

Hi, I do create a background job related to an event. Then in the meantime another event is fired and it requires me to delete the previously created background job before it does what it does. How can i do it? I dont have the id of the previously created job and even if i had it where would i store it so i can call the delete method with it.

Say there are five jobs in the background and i want to delete this specific one that has been created 20 mins ago and will run in 25 mins. How do i specify this single job(the one i want to delete) when the second event is fired?

thanks


3 Answer(s)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi uenlkr4e

    1- When creating a background job, generate a unique key for the job and store this key in a database or cache.

    string jobKey = $"Event_{eventType}";
    
    //Returns: Unique identifier of a background job.
    var jobId = await _backgroundJobManager.EnqueueAsync< MyJobMethod, UserIdentifier >(AbpSession.ToUserIdentifier());
    
    // Store jobId and jobKey in storage
    SaveJobKeyToStorage(jobKey, jobId);
    

    2- Delete the Job: When a new event is triggered, retrieve the stored key, find the job ID, and delete the job using BackgroundJob.Delete(jobId). You can place this code in second background job.

    var jobId = GetJobIdFromStorage(jobKey);
    if (jobId  != null)
    {
        await _backgroundJobManager.DeleteAsync(jobId);  // Delete the job
        RemoveJobKeyFromStorage(jobKey);  // Remove the key from storage
    }
    

    Here you can keep the jobId either in the database or in the cache. This may vary depending on the usage scenario. This is a sample code, you can change it according to the scenario. The business logic can be like this

  • User Avatar
    0
    uenlkr4e created

    Makes sense, thank you.

  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi

    If there's anything else we can assist you with, please don't hesitate to contact us. Have a great day!