Search code examples
phpdatabaselaravelcron

Laravel 6 | Configurable Jobs, attaching a model to a job


Problem

So I basically want to be able to have jobs that are attached to users and the users to be able to adjust the information about the job ( scheduled time, name, description, etc. ).

My ideas

I have thought about having one master job that would run through a table of jobs which has the time that they should run and all of the information, but this seems like a very janky way of doing this. I was wondering if there was a better alternative, I know theirs already job monitoring packages out there but none seem to be engineered to showing the customer and more engineered to showing the developers.

Question

So is there some way of a user being attached to certain jobs, while also being able to configure the date/time that it gets ran? The format I want to try to get is shown below.

[
    "id" => 1,
    "name" => "Test Job",
    "description" => "This is a test job.",
    "instigator_id" => 58,
    "time_scheduled" => "INSERT CARBON DATE HERE",
    "internal" => false,
    "date_created" => "",
    "last_updated" => ""
]

Solution

  • In that case it doesn't have to be a task scheduler. You are actually looking for an interface to dispatch jobs. Which means you can call dispatch from a controller. And then you could lookup the current jobs in the table. If you link the jobs using an abstract base job. Which is related to a user. If the job has any related other models or serialized models. you can attach them to the job. This way you might filter jobs on the queue, based on your criteria.

    Every model you assign as a public property from the constructor, will be automatically serialized and deserialized (As long as you will use the SerializesModels trait on your job)

    Jobs automatically can serialize eloquent models. If you would have a custom class this can be done as well. You just need to implement the Serializable interface

    Then if a job, might consume and process data. you should implement and restart() method. or something. that might save the data that could be saved, and spawn or schedule a new job.

    However, if you want to make an interruptable job, as you want to cancel it, during run. as you are saying, you will probaly have to implement something like that. That will check if anyone requested an interrupt.

    This can be done many ways, and depends on the scale of your solution. A simple way would be using locks using the Cache Driver. But on high load, this might bring some back draws.