Geen omschrijving

ActionScheduler_OptionLock.php 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. /**
  3. * Provide a way to set simple transient locks to block behaviour
  4. * for up-to a given duration.
  5. *
  6. * Class ActionScheduler_OptionLock
  7. * @since 3.0.0
  8. */
  9. class ActionScheduler_OptionLock extends ActionScheduler_Lock {
  10. /**
  11. * Set a lock using options for a given amount of time (60 seconds by default).
  12. *
  13. * Using an autoloaded option avoids running database queries or other resource intensive tasks
  14. * on frequently triggered hooks, like 'init' or 'shutdown'.
  15. *
  16. * For example, ActionScheduler_QueueRunner->maybe_dispatch_async_request() uses a lock to avoid
  17. * calling ActionScheduler_QueueRunner->has_maximum_concurrent_batches() every time the 'shutdown',
  18. * hook is triggered, because that method calls ActionScheduler_QueueRunner->store->get_claim_count()
  19. * to find the current number of claims in the database.
  20. *
  21. * @param string $lock_type A string to identify different lock types.
  22. * @bool True if lock value has changed, false if not or if set failed.
  23. */
  24. public function set( $lock_type ) {
  25. return update_option( $this->get_key( $lock_type ), time() + $this->get_duration( $lock_type ) );
  26. }
  27. /**
  28. * If a lock is set, return the timestamp it was set to expiry.
  29. *
  30. * @param string $lock_type A string to identify different lock types.
  31. * @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire.
  32. */
  33. public function get_expiration( $lock_type ) {
  34. return get_option( $this->get_key( $lock_type ) );
  35. }
  36. /**
  37. * Get the key to use for storing the lock in the transient
  38. *
  39. * @param string $lock_type A string to identify different lock types.
  40. * @return string
  41. */
  42. protected function get_key( $lock_type ) {
  43. return sprintf( 'action_scheduler_lock_%s', $lock_type );
  44. }
  45. }