Community

Getting started with Scheduler for task automation

Hey guys, I need a little help getting started with Scheduler for a fairly straightforward use case. Basically, every Sunday at 5 PM I want to email site users a list of their weekly activities. The following will be my cron job:

0 17 * * 0 php -q /www/assets/components/scheduler/run.php

I have a snippet that handles all the logic, namely building the activity list for each user and sending emails via modMail. Here it is in a nutshell:

// ...
foreach ($members as $member) {
  // grab list of upcoming activities for the current member
  $activities = $xyz->getUpcomingActivities($member->get('id'));

  if (empty($activities)) {
      continue;
  }

  // set mail fields
  $mailBody = array(
    'firstname' => $xyz->getUserInfo($member->get('id'), 'firstname'),
    'subject'   => 'Your upcoming activities',
    'list'      => $xyz->listUpcomingActivities($rowTpl, $activities)    
  );

  $modx->getService('mail', 'mail.modPHPMailer');
  $modx->mail->set(modMail::MAIL_BODY, $modx->getChunk($outerTpl, $mailBody));
  // ...  

  // send mail
  if (!$modx->mail->send()) {
      // log errors
      $run->addError('mail_error', array(
        'error_number' => rand(0, 99999)
      ));

    continue;
  }
}

I’ve manually set up a task in the component, referencing that snippet, but I’m not sure what time to specify. Beyond this, It’s not clear how the rest comes together. Unlike the example in the docs, this snippet doesn’t depend on user interactions.

If you have a fixed time and day the task needs to execute, Scheduler may be the wrong hammer.

Scheduler is for tasks that need to happen in the background, potentially a little in the future. It’s a simple message queue. Someone signs up, so you schedule a personalised welcome email 3 hours later. An activity is scheduled for next week, so you schedule a reminder the day before. That’s the type of use case Scheduler is for.

Schedulers’ cron job should be triggered every minute so it can check every minute if any new tasks were added to the queue; that you’re indicating it to only run at a specific time is a great indication you’re not looking for a message queue.

The use case you describe “sunday at 5pm” is simply a cron job. There’s a CronManager extra that may be better suited.

You could make it work with Scheduler if you really want to. Schedule your task for sunday 5pm through the dashboard, and make the task repeat itself. See scheduling a task. You already have access to the $task object in a snippet, so $task->schedule($nextRunTime, []); where $nextRunTime is a (unix) timestamp for the next time it should run.

1 Like

Thanks Mark. That’s what I suspected. I’ll take a look a the CronManager extra. It sounds more in line with what I need.

Thanks again, Mark. CronManager turned out to be useful indeed.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.