问题
I am writing Laravel json API on MySQL. Imagine user creates record inside my database. What I want to do is perform some kind of operation 24 hours after this record is created. I can achieve this using : AfterInsertJob::dispatch()->delay(now()->addHours(24));
. But I need to perform this operation again and again until record exists. So how can I do that? Should I dispatch job inside job? I mean Should I dispatch AfterInsertJob
inside AfterInsertJob
? I could use Schedule
but then how to stop that schedule from AfterInsertJob
?
回答1:
you can in AfterInsertJob->handle, on execution, create new queue:
$need_to_work = true;
.....
if( $need_to_work ){
AfterInsertJob::dispatch()->delay(3);
}
回答2:
Why using a job to to the Task. Just run a scheduled command which checks whatever requirement you have.
Add a flag on the record the user creates. Check this flag in the command you write and perform the task required. If the user does whatever he needs to to, set the flag and your command will ignore this entry. If not it will be done until it is set.
If it is required exactly 24 hours after creation you can check creation date (and multiple of that) and the flag. But there are surly other ways too.
Update:
After reading your comment, I have another idea which can suit your needs better. You can use two things.
- delay
- number of retries / max attempts
delay is a method called why dispatching
max attempts is a proptery of the job class by the name of ´tries`
Your job will check whatever it has to check, and if the requirements are NOT met by the user you will let the job fail. If that is so it will be pushed back onto the queue with the delay of 24 hours. This will repeat until the number of "max attempts" has been reached.
来源:https://stackoverflow.com/questions/55303635/repeatable-job-for-laravel-json-api