Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • David Armitage 485 posts 2042 karma points
    Jun 12, 2021 @ 12:04
    David Armitage
    0

    Creating Scheduled Tasks in Umbraco 9

    Hi Guys,

    Another Umbraco 9 question for the community.

    How to create scheduled tasks?

  • Mathias Hove 11 posts 71 karma points
    Jun 12, 2021 @ 12:23
    Mathias Hove
    100

    Hi. In Umbraco 9 you use the implementation called RecurringHostedServiceBase.

    This is essentially a hosted service, which came with Asp.net core.

    Here is an example of the a scheduled task.

    using System;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Logging;
    using Umbraco.Cms.Infrastructure.HostedServices;
    
        namespace {namespace].HostedServices
        {
            public class AnalyticsDataPersisterSchedule : RecurringHostedServiceBase
            {
                private readonly ILogger<AnalyticsDataPersisterSchedule> _logger;
    
                public AnalyticsDataPersisterSchedule(ILogger<AnalyticsDataPersisterSchedule> logger)
                    : base(TimeSpan.FromMinutes(2),
                        TimeSpan.FromMinutes(2))
                {
                    _logger = logger;
                }
    
                public override async Task PerformExecuteAsync(object state)
                {
                    try
                    {
                        // your thing
                    }
                    catch (Exception e)
                    {
                        _logger.LogError("exception when persisting collections: {exception}", e.ToString());
                    }
                }
            }
        }
    

    This class has to be registered in the DI/IOC container. This can be done in a composer class

    public class IoCComposer : IComposer
    {
        public void Compose(IUmbracoBuilder builder)
        {
            builder.Services.AddHostedService<AnalyticsDataPersisterSchedule>();
        }
    }
    
  • David Armitage 485 posts 2042 karma points
    Jun 12, 2021 @ 13:25
    David Armitage
    0

    Hi Mathias,

    Thanks for that. That worked a treat and was pretty simple to get set up.

    I actually wrote a short blog article to explain how to do this here. https://www.umbrajobs.com/blog/posts/2021/june/scheduled-or-recurring-tasks-in-umbraco-9/

    I also just got up and running with Hangfire with Umbraco 9.

    I am just cleaning up the loose ends then going to write a follow up article about this tomorrow.

    Thanks again for your quick response.

  • Huw Reddick 676 posts 2210 karma points
    Jun 12, 2021 @ 15:08
    Huw Reddick
    0

    Please post a link when cleaned up, I would be interested in seeing how you got hangfire working :)

  • David Armitage 485 posts 2042 karma points
    Jun 12, 2021 @ 15:29
    David Armitage
    0

    Almost there

    I am full up and running apart from adding some security. I am struggling with creating the HangfireAuthorizationFilter.

    The code I have so far. But I just cant seem to get the logged in user in the context.

    namespace Website.Core.Utils
    {
        public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
        {
            private string policyName;
    
            public HangfireAuthorizationFilter(string policyName, string test)
            {
                this.policyName = policyName;
            }
    
            public bool Authorize([NotNull] DashboardContext context)
            {
                var httpContext = context.GetHttpContext();
                var authService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>();
                bool success = authService.AuthorizeAsync(httpContext.User, this.policyName).ConfigureAwait(false).GetAwaiter().GetResult().Succeeded;
                return success;
            }
        }
    }
    

    This was Umbraco 8 code. I dont think we have access to the context in the same way so just trying to figure out the work around.

    namespace Website.Core.Utils
    {
        public class UmbracoAuthorizationFilter : IDashboardAuthorizationFilter
        {
            public bool Authorize(DashboardContext context)
            {
                var http = new HttpContextWrapper(HttpContext.Current);
                var ticket = http.GetUmbracoAuthTicket();
                http.AuthenticateCurrentRequest(ticket, true);
    
                var user = Current.UmbracoContext.Security.CurrentUser;
    
                return user != null && user.Groups.Any(g => g.Alias == "admin");
            }
        }
    }
    

    I will have blog article written up tomorrow.

    I might also create a stand alone ticket on Umbraco forum too for if anyone looks there.

    If anyone has any ideas about the above issue I am all ears.

    Regards

    David

  • Andy Butland 401 posts 2258 karma points MVP 4x hq c-trib
    Jun 12, 2021 @ 12:29
    Andy Butland
    2

    Hi David

    For background on scheduled tasks in V9 you should have a read about hosted services, which are a feature provided by the .NET 5 framework, and Umbraco are using.

    I'm not sure if they've been documented specifically for Umbraco yet, but if you don't mind digging into the source you can find some examples here (for example see HealthCheckNotifier).

    You can implement your own inheriting from the same class that this one does - RecurringHostedServiceBase which is provided in V9.

    Andy

  • David Armitage 485 posts 2042 karma points
    Jun 12, 2021 @ 13:26
    David Armitage
    0

    Thanks Andy.

  • David Armitage 485 posts 2042 karma points
    Jun 13, 2021 @ 04:34
    David Armitage
    0

    Hi All,

    As promised here is the blog article on how to get up and running with Hangfire on Umbraco 9.

    The good news it is so much easier than doing it in Umbraco 8. No messing around with the Owin startup etc.

    Here is he article. Is will probably take less than 30 mins to get up and running.

    https://www.umbrajobs.com/blog/posts/2021/june/umbraco-9-configuring-hangfire-scheduled-tasks/

    Regards

    David

Please Sign in or register to post replies

Write your reply to:

Draft