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

[8.x] Allow Unique Chained Jobs #37031

Closed
wants to merge 3 commits into from
Closed

[8.x] Allow Unique Chained Jobs #37031

wants to merge 3 commits into from

Conversation

craigh411
Copy link

@craigh411 craigh411 commented Apr 18, 2021

At the moment we can dispatch unique jobs by applying the ShouldBeUnique interface to the job, however, there isn't a way to do this with chained jobs.

I have a situation where I'm deploying code using chained jobs; the deployment can be activated via an API, scheduled or dispatched from a web interface. When this chain begins I am setting the deployment status to processing, which prevents other chains from dispatching, however, if the job does not start immediately it's possible for the chain to be dispatched multiple times and handling all the statuses to prevent jobs dispatching can quickly become confusing.

This PR adds a dispatchUnique() method for chained jobs in which you can pass in a name, id and uniqueFor:

$siteId = 1;
Bus::chain([
  new PrepareDeployment(),
  new Deploy()
])->dispatchUnique('deployment', $siteId, 3600);

A few notes:

  • The lock is automatically released on success and failure
  • The default duration of the lock is 3600 (1 hour), which should cover the processing period for most jobs, however, I do appreciate that is quite long.
  • The chain can be dispatched with just a name, (id is optional)
  • If a duplicate job is dispatched, null is returned, the thinking behind this is that you could do:
$chain = Bus::chain([
  new PrepareDeployment(),
  new Deploy()
])

if($chain->dispatchUnique('deployment')){
   // Chain is processing
} else {
  // throw duplicate chain exception
}

Let me know if there's anything you think can be improved.

- Checks that the chainLock property exists before trying to access it
@craigh411 craigh411 changed the title Allow Unique Chained Jobs [8.x] Allow Unique Chained Jobs Apr 18, 2021
@taylorotwell
Copy link
Member

Honestly - I would suggest just using database transaction locks (lockForUpdate) and dispatching the job within a transaction. You can set some value on the site to indicate it is deploying within the transaction. That should give you an atomic way to check if the site is already deploying and not deploy if it is.

@craigh411
Copy link
Author

Absolutely! That works really nicely.

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

Successfully merging this pull request may close these issues.

3 participants