最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to dynamically change the interval of a recurring message using scheduler? - Stack Overflow

programmeradmin2浏览0评论

I have a scheduler that sends a recurring message every five minutes to update some cached external data. I added a feature that allows a user to change this interval in the front-end. However, I am unable to change the schedule such that the recurring messages occurs according to the new interval.

I tried to get the existing schedule in order to clear the schedule and add a new recurring message with the new interval. Unfortunately, I am always creating a new schedule instead of getting the existing one. This would be fine if the message handler used the newly created schedule, but it continues to use the old scheduled messages instead. The schedule provider and the class that handles updating the schedule are given below. I also tried to make the schedule variable static, but this did not change my results. Even when using the PreRunEvent from the schedule's before function I am unable to get the existing schedule.

#[AsSchedule('update_cache')]
final class UpdateCacheTaskProvider implements ScheduleProviderInterface
{
    public function getSchedule(): Schedule
    {
        return $this->schedule ??= (new Schedule())->with(
            RecurringMessage::every($this->getRefreshRateInterval(), new UpdateCacheMessage())
        );
    }
}

class RefreshRateSubscriber implements EventSubscriberInterface
{
    public function __construct(private UpdateCacheTaskProvider $updateCacheTaskProvider) {}

    public function onRefreshRateChanged(RefreshRateChangedEvent $event): void
    {
        $this->updateCacheTaskProvider
            ->getSchedule()
            ->clear()
            ->add(RecurringMessage::every($event->getRefreshRateInterval(), new UpdateCacheMessage()));
    }

    public static function getSubscribedEvents(): array
    {
        return [
            RefreshRateChangedEvent::NAME => 'onRefreshRateChanged'
        ];
    }
}
发布评论

评论列表(0)

  1. 暂无评论