Create a named scheduled job?

Viewed 62

I need to create a scheduled task that executes 10mins from now. However, I may need to delete that job before it has been executed. I know you get a jobid when the job is created like this:

var jobId = BackgroundJob.Schedule<MyJob>(job => job.Execute(),TimeSpan.FromMinutes(10));

However, this would require storing the jobid in a DB or cache of some sort in order to delete it in the future.

Is it possible to name a scheduled job like you can with a reoccurring job? Ideally something like this:

BackgroundJob.Schedule<MyJob>("MyJobName", job => job.Execute(),TimeSpan.FromMinutes(10));

It would obviously need to throw an exception if that job name already exists, but it would allow people to use already known data to name their jobs vs. needing to keep another data store with stateful job ids.

1 Answers

As far as I know, this does not exist out of the box.

As a blind shot, I would try something like this, using the IMonitoringApi:

var api = JobStorage.Current.GetMonitoringApi();
var jobs = api.EnqueuedJobs(queue: "theQueue", from: 0, perPage: 1);
if (jobs.Count == 1)
{
    var jobId = jobs[0].Key;
    BackgroundJob.Delete(jobId);
}

This is assuming that you have a dedicated queue, "theQueue", to process that specific job.

If it is not a dedicated queue, for example "default", you will need to iterate on each job in the queue (api.EnqueuedCount("default") instead of 1), see if its method (and maybe parameters) match what you need, and delete the one which matches.

Related