Take the community feedback survey now.

Praful Jangid
Dec 7, 2019
  86
(0 votes)

Skip jobs to execute on specific day(s) of the week

Hi All,

Recently came across a requirement of skipping jobs execution on weekends. So, I thought why not allow editors to control all/any jobs to stop execute on specific days of week.

So, I took inspiration from @Paul's reply on this thread.

First, I created SelectionFactory for all existing jobs on StartPage (Home page), you can create this property on your setting item (as per your wish). Along with another property to select days of week to disable the jobs.

[Display(
    Name = "Scheduled jobs",
    Description = "Select jobs to stop execution on specific day",
    GroupName = Global.GroupNames.SiteSettings,
    Order = 1000)]
[SelectMany(SelectionFactoryType = typeof(ScheduledJobsSelectionFactory))]
public virtual string ScheduledJobs { get; set; }

[Display(
    Name = "Skip job execution on day(s)",
    Description = "Select days on which you don't want to execute jobs",
    GroupName = Global.GroupNames.SiteSettings,
    Order = 1010)]
[SelectMany(SelectionFactoryType = typeof(WeekDaysSelectionFactory))]
public virtual string SkipJobExecutionOnDays { get; set; }

Which something will look like this in our CMS (in below image).

[I selected some jobs and days to disable].

*I will add code of selection factories at the end

Next, our scheduled job that will scan all our jobs and check if their next execution is fallin on the skip day, then just updated next execution field and saved back. Here this code contains function to get HomePage.

[ScheduledPlugIn(DisplayName = "Skip JobExecution Scheduled Job")]
public class SkipJobExecutionScheduledJob : ScheduledJobBase
{
    private bool _stopSignaled;
    private readonly IContentLoader _contentLoader;
    private readonly IScheduledJobRepository _scheduledJobRepository;

    public SkipJobExecutionScheduledJob(
        IContentLoader contentLoader,
        IScheduledJobRepository scheduledJobRepository)
    {
        _contentLoader = contentLoader ?? throw new ArgumentNullException(nameof(contentLoader));
        _scheduledJobRepository = scheduledJobRepository ?? throw new ArgumentNullException(nameof(scheduledJobRepository));
        IsStoppable = true;
    }

    /// <summary>
    /// Called when a user clicks on Stop for a manually started job, or when ASP.NET shuts down.
    /// </summary>
    public override void Stop()
    {
        _stopSignaled = true;
    }

    /// <summary>
    /// Called when a scheduled job executes
    /// </summary>
    /// <returns>A status message to be stored in the database log and visible from admin mode</returns>
    public override string Execute()
    {
        //Call OnStatusChanged to periodically notify progress of job for manually started jobs
        OnStatusChanged($"Starting execution of {this.GetType()}");

        var sb = new StringBuilder();
        var homePage = this.GetHomePage();
        if (homePage == null) return $"Could not retrieve site settings";

        var jobs = homePage.ScheduledJobs?.Split(',').ToList();
        var jobToDisable = jobs?.Select(x => this._scheduledJobRepository.Get(Guid.Parse(x))).ToList()
               ?? new List<ScheduledJob>();
        var skipJobExecutionOnDays = homePage.SkipJobExecutionOnDays?.Split(',').ToList();
        if (jobToDisable.Count > 0 && skipJobExecutionOnDays != null && skipJobExecutionOnDays.Count > 0)
        {
            foreach (var job in jobToDisable)
            {
                if (skipJobExecutionOnDays.Contains(job.NextExecution.DayOfWeek.ToString()))
                {
                    job.NextExecution = job.NextExecution.AddDays(1);
                    this._scheduledJobRepository.Save(job);
                    OnStatusChanged($"Updated \"{job.Name}\" to run on \"{job.NextExecution}\"");
                    sb.AppendLine($"Updated \"{job.Name}\" to run on \"{job.NextExecution}\"");
                }

                //For long running jobs periodically check if stop is signaled and if so stop execution
                if (_stopSignaled)
                {
                    return "Stop of job was called";
                }
            }
        }

        //For long running jobs periodically check if stop is signaled and if so stop execution
        if (_stopSignaled)
        {
            return "Stop of job was called";
        }
        var rtn = sb.ToString();
        if (rtn == string.Empty)
        {
            rtn = "Job completed successfully. No updates required.";
        }
        return rtn;
    }

    private StartPage GetHomePage()
    {
        var pageLink = SiteDefinition.Current.StartPage;
        if (pageLink == null || pageLink == ContentReference.EmptyReference)
            return null;

        this._contentLoader.TryGet(pageLink, out PageData page);

        if (page == null)
            return null;

        return this.GetHomePage(page);
    }

    private StartPage GetHomePage(PageData page)
    {
        if (page == null)
            return null;

        if (page is StartPage homePage)
            return homePage;

        homePage = this._contentLoader
                .GetAncestors(page.ContentLink)
                .FirstOrDefault(x => x is StartPage)
            as StartPage;

        return homePage;
    }
}

In addition, I am adding selection factory code here.

public class ScheduledJobsSelectionFactory: ISelectionFactory
{
    public Injected<IScheduledJobRepository> ScheduledJobRepository { get; set; }

    public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
    {
        var scheduledJobs = this.ScheduledJobRepository.Service.List();

        var selections =
            scheduledJobs
                .Select(x => new SelectItem
                {
                    Text = x.Name,
                    Value = x.ID.ToString()
                })
                .ToList();

        return selections;
    }
}
public class WeekDaysSelectionFactory : ISelectionFactory
{
    public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
    {
        return Enum
            .GetNames(typeof(DayOfWeek))
            .Select(x => new SelectItem { Text = x, Value = x })
            .ToList();
    }
}

On a special note, you can add fields for time range to skip in that duration (Stop Execution Time and Start Execution Time).

Special Note: This implementation is more focused with single site implementation. If you have jobs that are site specific you can follow comment by @Antti (below in comments).

And to restrict the access you can follow this post.

Reach-out to me if you have any question or concern :)

Thanks & Regards

Praful Jangid

Happy Coding!

Dec 07, 2019

Comments

Please login to comment.
Latest blogs
A day in the life of an Optimizely OMVP - Opticon London 2025

This installment of a day in the life of an Optimizely OMVP gives an in-depth coverage of my trip down to London to attend Opticon London 2025 held...

Graham Carr | Oct 2, 2025

Optimizely Web Experimentation Using Real-Time Segments: A Step-by-Step Guide

  Introduction Personalization has become de facto standard for any digital channel to improve the user's engagement KPI’s.  Personalization uses...

Ratish | Oct 1, 2025 |

Trigger DXP Warmup Locally to Catch Bugs & Performance Issues Early

Here’s our documentation on warmup in DXP : 🔗 https://docs.developers.optimizely.com/digital-experience-platform/docs/warming-up-sites What I didn...

dada | Sep 29, 2025

Creating Opal Tools for Stott Robots Handler

This summer, the Netcel Development team and I took part in Optimizely’s Opal Hackathon. The challenge from Optimizely was to extend Opal’s abiliti...

Mark Stott | Sep 28, 2025