coravel icon indicating copy to clipboard operation
coravel copied to clipboard

Extend Coravel Schedule With CoravelJobAttrbutes

Open linfeng627 opened this issue 1 month ago • 0 comments

    [AttributeUsage(AttributeTargets.Class)]
    public class CoravelJobAttrbutes : Attribute
    {
        [Required]
        public string Cron { get; }

        public CoravelJobAttrbutes(string cron)
        {
            var values = cron.Split(' ');
            if (values.Length != 5)
            {
                throw new Exception($"Cron expression '{cron}' is invalid.");
            }
            Cron = cron;
        }
    }

    public static class CoravelSchedulingExtension
    {

        public static IServiceCollection AddCoravelJob(this IServiceCollection services) 
        {
            var coravelJobsList = Assembly.GetExecutingAssembly().GetTypes().Where(p => p.GetCustomAttribute<CoravelJobAttrbutes>() != null);
            if (coravelJobsList != null && coravelJobsList.Any())
            {
                foreach (var item in coravelJobsList)
                {
                    services.AddTransient(item);
                }
            }
            services.AddScheduler();
            return services;
        }

        public static IServiceProvider UseCoravelJob(this IServiceProvider service)
        {
            var coravelJobsList = Assembly.GetExecutingAssembly().GetTypes().Where(p => p.GetCustomAttribute<CoravelJobAttrbutes>() != null);
            if (coravelJobsList != null && coravelJobsList.Any())
            {
                service.UseScheduler(p =>
                {
                    foreach (var item in coravelJobsList)
                    {
                        var cronStr = item.GetCustomAttribute<CoravelJobAttrbutes>()!.Cron;
                        p.ScheduleInvocableType(item).Cron(cronStr);
                    }
                });
            }
            return service;
        }
    }

     // Program.cs
    builder.Services.AddCoravelJob();
    
    app.Services.UseCoravelJob();


    [CoravelJobAttrbutes(cron: "*/10 * * * *")]
    public class CoravelTestJob : Coravel.Invocable.IInvocable
    {
        public async Task Invoke()
        {
            // TODO...
            Console.WriteLine("CoravelTestJob ");
        }
    }


linfeng627 avatar May 17 '24 09:05 linfeng627