jamesmh / coravel

Near-zero config .NET library that makes advanced application features like Task Scheduling, Caching, Queuing, Event Broadcasting, and more a breeze!
https://docs.coravel.net/Installation/
MIT License
3.91k stars 257 forks source link

Extend Coravel Schedule With CoravelJobAttrbutes #387

Open linfeng627 opened 6 months ago

linfeng627 commented 6 months ago
    [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 ");
        }
    }