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.63k stars 243 forks source link

Scheduling async invocables with parameters #355

Closed vininew921 closed 4 months ago

vininew921 commented 4 months ago

I'm trying to schedule a Invocable on startup, but it is an async invocable and has some parameters. How can I achieve this? I couldn't find any examples in here or the documentation.

Startup

foreach (Job job in jobs)
{
    //Try removing past scheduled tasks, just in case
    (scheduler as Scheduler)!.TryUnschedule(job.Id.ToString());

    //Schedule JobInvocable with the CronExpression defined in the database
    IScheduledEventConfiguration? scheduleEvent = scheduler
                                                    .ScheduleWithParams<JobInvocable>(job.Id) //Make this async
                                                    .Cron(job.CronExpression);

    //Assign job id to prevent overlap of the same job
    scheduleEvent.PreventOverlapping(job.Id.ToString());
}

Invocable

public class JobInvocable : IInvocable
{
    private DataProvider _dataProvider;
    private Guid _jobId;

    public JobInvocable(DataProvider dataProvider, Guid jobId)
    {
        _dataProvider = dataProvider;
        _jobId = jobId;
    }

    public async Task Invoke()
    {
        Job? jobToInvoke = await _dataProvider.Jobs.FirstOrDefaultAsync(x => x.Id == _jobId);
        Console.WriteLine($"Executing {_jobId}");
        //To do -> execute job specifics
    }
}
jamesmh commented 4 months ago

I don't understand why the call to ScheduleWithParams() has to be async - I think I'll need some more context to understand what you're looking for. Thanks πŸ™‚

vininew921 commented 4 months ago

I misunderstood how it worked, sorry. Everything worked as expected.

jamesmh commented 4 months ago

Okay - great πŸ™‚. Let me know if things don't work out πŸ‘