Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend Coravel Schedule With CoravelJobAttrbutes #387

Open
linfeng627 opened this issue May 17, 2024 · 0 comments
Open

Extend Coravel Schedule With CoravelJobAttrbutes #387

linfeng627 opened this issue May 17, 2024 · 0 comments

Comments

@linfeng627
Copy link

linfeng627 commented May 17, 2024

    [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 ");
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant