How to assign custom id for Scheduled job like the Recurring job?

Hi,
My question is as titled, is it possible to assign a custom id for the Scheduled job?

The reason for asking this:

  1. My entire mission, is to set hangfire at a separate machine.
  2. I have a web page, allowing user to set ‘Start Date’, ‘End Date’ and ‘Crontab expression’
  3. Now, based on 2), i got to have three jobs in hangfire
    a. One job delayed to start at ‘Start Date’
    b. The job of a) is to run the crontab
    c. One job delayed to remove the job at b)

Creating a new one is fine. But during edit, it puzzles me.
Q: how to edit a scheduled job? Some suggests to ‘delete’ then ‘create a new one’

But the thing is, how to know the id of the scheduled job? Currently, the BackgroundJob returns an Id, which, seems that i need to store that id in a new table, such that in future, i can refer back this id to ‘delete’ it before creating a new one.

If i am able to assign a custom id, that at least save me from creating one table, as i am able to associate that ID with the ids from other table.

Any suggestion is appreciated

How to assign custom id for Scheduled job like the Recurring job?

I don’t think this is possible, nor is it probably a good idea.

The reason for this is that it also heavily affects the storage part. For instance the job ID needs to be unique and in many cases is used as a key for a lot of things. For instance in the mongo storage implementation it is set to the object ID of the Mongo bson document that holds the job definition. While it is possible to use your own ID it does come with a lot of risks and problems if not done correctly.

The problem only gets worse if you then factor in that the job id mechanism is different for other storage options so what might work on one would not work on others (which is why it is the storage module that ‘generates’ the job ID).

I had similar problem with you and found following solution. Maybe it is not a proper approach to utilize Hangfire but it works at least.

My job definition has a property called iteration. It can have following values

  • 0 - infinite recurring job
  • 1 - delayed job
  • other numbers - recurring job

and I implemented a custom attribute as following and it intercepts onCreating hook. Basically, it checks whether the job’s iteration value is exceeded or not. If it was exceeded, it removes the recurring job definition.

var recurringJobParams = JobStorage.Current.GetConnection().GetAllEntriesFromHash(recurringJob);

        if (recurringJobParams.ContainsKey("iteration"))
        {
            var currentIteration = Convert.ToInt32(recurringJobParams["iteration"]);

            if (job.Plan.Iteration - currentIteration == 0)
            {
                RecurringJob.RemoveIfExists(jobId);
                filterContext.Canceled = true;
            }
        }
        else
        {
                recurringJobParams.Add("iteration", "1");
        }