Virtual Happy Hour this month, Jun 28, we'll be getting a sneak preview at our soon to launch SaaS CMS!

Try our conversational search powered by Generative AI!

How to tell if a scheduled job has been manually triggered?

Vote:
 

Using Optimizely CMS 12, how can I in code that's being run in a scheduled job tell if the job was triggered manually in the CMS UI or by the scheduler?

In "the old days" we did this by checking if PrincipalInfo.CurrentPrincipal.Identity?.IsAuthenticated was true or not but I can't find a similar way to do this in newer versions of the CMS.

I've tried using the IHttpContextAccessor but HttpContext is always null, unless I'm doing something wrong. 

Does anyone know a solution to this problem?

Best regards

Martin

#320980
Apr 24, 2024 21:14
Vote:
 

Hi Martin,

I think that there is no default way to detect if job is run manually in Execute method of your job. With Optimizely CMS new version, Jobs run without user context for both manual and scheduled mode. So you cannot check Identity or Current Http Context for it.

But you can get this value through job trigger option such as Scheduler, User or Restart in the job executor level as following, not in scheduled job level.

public class CustomScheduledJobExecutor : DefaultScheduledJobExecutor
{
    public CustomScheduledJobExecutor(SchedulerDB dataAccess, IScheduledJobRepository repository, IScheduledJobLogRepository logRepository, IScheduledJobFactory jobFactory, IEventRegistry eventRegistry, IScheduledJobEventsRaiser scheduledJobEvents, FailedScheduledJobRegistry failedJobRegistry, SchedulerOptions schedulerOptions, IBackgroundContextFactory backgroundContextFactory) : base(dataAccess, repository, logRepository, jobFactory, eventRegistry, scheduledJobEvents, failedJobRegistry, schedulerOptions, backgroundContextFactory)
    {
    }

    public override Task<JobExecutionResult> StartAsync(ScheduledJob job, JobExecutionOptions options, CancellationToken cancellationToken)
    {
        //Check if job is run by user
        if (options.Trigger == ScheduledJobTrigger.User)
        {
            //TODO: Add custom logic here
        }    
        return base.StartAsync(job, options, cancellationToken);
    }
}

You can try to pass this value into certain temporary storage for example if you want to check this value in Scheduled Job level or you can add your logic right here in Executor level if you could

#321020
Apr 25, 2024 8:44
Vincent - Apr 26, 2024 6:12
Thanks for sharing, I like this approach.
Vote:
 

Works like a charm, thanks a lot!

#321280
Apr 30, 2024 12:17
Binh Nguyen Thi - May 03, 2024 4:44
Nice to hear that!
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.