Run once a week at midnight on Sunday morning

@return $this
187849
public function weekly()
    {
        $this->setScheduleMonth(self::ANY);
        $this->setScheduleWeek(self::ANY);
        $this->setScheduleDayOfMonth(self::ANY);
        $this->setScheduleDayOfWeek(Day::SUNDAY);
        $this->setScheduleHour(0);
        $this->setScheduleMinute(0);

        return $this;
    }
1050561
public function eachDayOfWeek($dayOfWeek, \Closure $callback)
    {
        $start = $this->startDate->copy();
        if ($start->dayOfWeek !== $dayOfWeek) {
            $start->next($dayOfWeek);
        }

        if ($start < $this->endDate) {
            $period = new static($start, $this->endDate);

            $period->eachDays(CarbonDate::DAYS_PER_WEEK, function (CarbonPeriod $period) use ($callback) {
                $callback(new static($period->start(), $period->start()->addDay()));
            });
        }

        return $this;
    }
665851
public function schedule($when)
    {
        if (is_numeric($when)) {
            $dt = new DateTime;
            $dt->setTimestamp($when);
        } else {
            $dt = new DateTime($when);
        }

        $this->scheduled_at = $dt->format(DateTime::ISO8601);

        return $this;
    }
872345
public function skipMissedSchedules()
    {
        $schedules = Mage::getModel('cron/schedule')->getCollection()
            ->addFieldToFilter('status', Aoe_Scheduler_Model_Schedule::STATUS_PENDING)
            ->addFieldToFilter('scheduled_at', array('lt' => strftime('%Y-%m-%d %H:%M:%S', time())))
            ->addOrder('scheduled_at', 'DESC')
            ->load();

        Mage::getSingleton('cron/schedule')->getResource()->beginTransaction(TRUE);
        try {
            $seenJobs = array();
            foreach ($schedules as $key => $schedule) {
                /* @var Aoe_Scheduler_Model_Schedule $schedule */
                if (isset($seenJobs[$schedule->getJobCode()])) {
                    $schedule
                        ->setMessages('Multiple tasks with the same job code were piling up. Skipping execution of duplicates.')
                        ->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_SKIP_PILINGUP);
                    $updated = $schedule->getResource()->trySetJobStatusAtomic(
                        $schedule->getId(),
                        $schedule->getStatus(),
                        Aoe_Scheduler_Model_Schedule::STATUS_PENDING
                    );
                    if ($updated) {
                        $schedule->save();
                    }
                } else {
                    $seenJobs[$schedule->getJobCode()] = 1;
                }
            }
            Mage::getSingleton('cron/schedule')->getResource()->commit();
        } catch (Exception $e) {
            Mage::getSingleton('cron/schedule')->getResource()->rollBack();
            throw $e;
        }

        return $this;
    }
858101
public function cron() {
    // @todo Use config to stop/resume the runner.
    $prefix = 'openy_cron_';
    /** @var OpenyCronServiceInterface $service */
    foreach ($this->cronServices as $periodicity => $services) {
      foreach ($services as $service) {
        $name = $prefix . $service->_serviceId;
        $last_run = $this->state->get($name);
        if ((REQUEST_TIME - $last_run) > $periodicity) {
          // @todo Fix DI on OpenY sprint.
          \Drupal::logger("openy_cron")->info('Service %service has been started.', ['%service' => $service->_serviceId]);
          Timer::start($name);
          $service->runCronServices();
          $execution_time = Timer::read($name) / 1000;
          $this->state->set($name, REQUEST_TIME);
          \Drupal::logger("openy_cron")->info('Service %service has been finished. Execution time: %time sec.', ['%service' => $service->_serviceId, '%time' => $execution_time]);
          Timer::stop($name);
        }
      }
    }
  }
415733
public function weekOfYear($week)
    {
        $this->setScheduleMonth(self::NONE);
        $this->setScheduleWeek($this->parseTimeParameter($week));
        $this->setScheduleDayOfMonth(self::ANY);
        $this->setScheduleDayOfWeek(Day::SUNDAY);
        $this->setScheduleHour(0);
        $this->setScheduleMinute(0);

        return $this;
    }
671374
public function getNextRunDate(): Carbon
    {
        $cron = CronExpression::factory($this->getExpression());
        $nextRun = Carbon::instance($cron->getNextRunDate());
        if ($this->timezone) {
            $nextRun->setTimezone($this->timezone);
        }

        return $nextRun;
    }
59275
public function setData($value) : ScheduledJob
    {
        $this->validateJson($value);

        if ($this->data['data'] !== $value) {
            $this->data['data'] = $value;
            $this->setModified('data');
        }

        return $this;
    }
427023
public function reset(): Matomo
    {
        $this->_period = self::PERIOD_DAY;
        $this->_date = '';
        $this->_rangeStart = 'yesterday';
        $this->_rangeEnd = null;

        return $this;
    }
22991
public function plusWeeks(int $weeks) : YearWeek
    {
        if ($weeks === 0) {
            return $this;
        }

        $mondayOfWeek = $this->atDay(DayOfWeek::MONDAY)->plusWeeks($weeks);

        return $mondayOfWeek->getYearWeek();
    }
931424
protected function startScheduler()
    {
        $this->now = new \DateTime('now', new \DateTimeZone('UTC'));

        $periodStart = clone $this->now;
        $periodStart->modify('-'.$this->interval.' minutes');

        $scheduler = new Scheduler();
        $scheduler->setStatus(Scheduler::STATUS_RUNNING);
        $scheduler->setExecutionStart($this->now);
        $scheduler->setPeriodStart($periodStart);
        $scheduler->setPeriodEnd($this->now);
        $scheduler->setPeriodInterval($this->interval);

        $this->em->persist($scheduler);
        $this->em->flush();

        return $scheduler;
    }
19430
public function runNow($tryLockJob = true, $forceRun = false)
    {
        // Check the user running the cron is the one defined in config
        if (!$this->checkRunningAsCorrectUser()) {
            $this->setStatus(self::STATUS_SKIP_WRONGUSER)->save();
            return $this;
        }

        // if this schedule doesn't exist yet, create it
        if (!$this->getCreatedAt()) {
            $this->schedule();
        }

        if (!$forceRun) {
            // lock job (see below) prevents the exact same schedule from being executed from more than one process (or server)
            // the following check will prevent multiple schedules of the same type to be run in parallel
            $processManager = Mage::getModel('aoe_scheduler/processManager'); /* @var $processManager Aoe_Scheduler_Model_ProcessManager */
            if ($processManager->isJobCodeRunning($this->getJobCode(), $this->getId())) {
                $this->getResource()->trySetJobStatusAtomic(
                    $this->getId(),
                    Aoe_Scheduler_Model_Schedule::STATUS_SKIP_OTHERJOBRUNNING,
                    Aoe_Scheduler_Model_Schedule::STATUS_PENDING
                );
                $this->log(sprintf('Job "%s" (id: %s) will not be executed because there is already another process with the same job code running. Skipping.', $this->getJobCode(), $this->getId()));
                return $this;
            }
        }

        // lock job requires the record to be saved and having status Aoe_Scheduler_Model_Schedule::STATUS_PENDING
        // workaround could be to do this: $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_PENDING)->save();
        $this->jobWasLocked = false;
        if ($tryLockJob && !$this->tryLockJob()) {
            // another cron started this job intermittently, so skip it
            $this->jobWasLocked = true;
            $this->log(sprintf('Job "%s" (id: %s) is locked. Skipping.', $this->getJobCode(), $this->getId()));
            return $this;
        }

        try {
            // Track the last user to run a job
            $this->setLastRunUser();

            $job = $this->getJob();

            if (!$job) {
                Mage::throwException(sprintf("Could not create job with jobCode '%s'", $this->getJobCode()));
            }

            $startTime = time();
            $this
                ->setExecutedAt(strftime('%Y-%m-%d %H:%M:%S', $startTime))
                ->setLastSeen(strftime('%Y-%m-%d %H:%M:%S', $startTime))
                ->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_RUNNING)
                ->setHost(gethostname())
                ->setPid(getmypid())
                ->save();

            Aoe_Scheduler_Helper_GracefulDead::configure();

            Mage::register('currently_running_schedule', $this);

            Mage::dispatchEvent('cron_' . $this->getJobCode() . '_before', array('schedule' => $this));
            Mage::dispatchEvent('cron_before', array('schedule' => $this));

            Mage::unregister('current_cron_task');
            Mage::register('current_cron_task', $this);

            $this->log('Start: ' . $this->getJobCode());

            $this->_startBufferToMessages();
            $this->jobErrorContext();

            $callback = $job->getCallback();

            try {
                // this is where the magic happens
                $messages = call_user_func_array($callback, array($this));

                $this->restoreErrorContext();
                $this->_stopBufferToMessages();
            } catch (Exception $e) {
                $this->restoreErrorContext();
                $this->_stopBufferToMessages();
                throw $e;
            }

            $this->log('Stop: ' . $this->getJobCode());

            if (!empty($messages)) {
                if (is_object($messages)) {
                    $messages = get_class($messages);
                } elseif (!is_scalar($messages)) {
                    $messages = var_export($messages, 1);
                }
                $this->addMessages(PHP_EOL . '---RETURN_VALUE---' . PHP_EOL . $messages);
            }

            // schedules can report an error state by returning a string that starts with "ERROR:", "NOTHING", or "REPEAT"
            // or they can set set the status directly to the schedule object that's passed as a parameter
            if ((is_string($messages) && strtoupper(substr($messages, 0, 6)) == 'ERROR:') || $this->getStatus() === Aoe_Scheduler_Model_Schedule::STATUS_ERROR) {
                $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_ERROR);
                Mage::helper('aoe_scheduler')->sendErrorMail($this, $messages);
                Mage::dispatchEvent('cron_' . $this->getJobCode() . '_after_error', array('schedule' => $this));
                Mage::dispatchEvent('cron_after_error', array('schedule' => $this));
            } elseif ((is_string($messages) && strtoupper(substr($messages, 0, 7)) == 'NOTHING') || $this->getStatus() === Aoe_Scheduler_Model_Schedule::STATUS_DIDNTDOANYTHING) {
                $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_DIDNTDOANYTHING);
                Mage::dispatchEvent('cron_' . $this->getJobCode() . '_after_nothing', array('schedule' => $this));
                Mage::dispatchEvent('cron_after_nothing', array('schedule' => $this));
            } elseif ((is_string($messages) && strtoupper(substr($messages, 0, 6)) == 'REPEAT') || $this->getStatus() === Aoe_Scheduler_Model_Schedule::STATUS_REPEAT) {
                $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_REPEAT);
                Mage::dispatchEvent('cron_' . $this->getJobCode() . '_after_repeat', array('schedule' => $this));
                Mage::dispatchEvent('cron_after_repeat', array('schedule' => $this));
            } else {
                $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_SUCCESS);
                Mage::dispatchEvent('cron_' . $this->getJobCode() . '_after_success', array('schedule' => $this));
                Mage::dispatchEvent('cron_after_success', array('schedule' => $this));

                $this->scheduleOnSuccessDependencies();
            }

        } catch (Exception $e) {
            $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_ERROR);
            $this->addMessages(PHP_EOL . '---EXCEPTION---' . PHP_EOL . $e->__toString());
            Mage::dispatchEvent('cron_' . $this->getJobCode() . '_exception', array('schedule' => $this, 'exception' => $e));
            Mage::dispatchEvent('cron_exception', array('schedule' => $this, 'exception' => $e));
            Mage::helper('aoe_scheduler')->sendErrorMail($this, $e->__toString());
        }

        $this->setFinishedAt(strftime('%Y-%m-%d %H:%M:%S', time()));
        $this->setMemoryUsage(memory_get_peak_usage(true) / pow(1024, 2));  // convert bytes to megabytes
        Mage::dispatchEvent('cron_' . $this->getJobCode() . '_after', array('schedule' => $this));
        Mage::dispatchEvent('cron_after', array('schedule' => $this));

        $this->save();
        Mage::unregister('currently_running_schedule');

        return $this;
    }
975349
public function setByWeekNo($value)
    {
        if (!is_integer($value) || $value > 53 || $value < -53 || $value === 0) {
            throw new InvalidArgumentException('Invalid value for BYWEEKNO');
        }

        $this->byWeekNo = $value;

        $this->canUseBySetPos = true;

        return $this;
    }
1236524
public function makeSchedule()
    {
        // Pull out the first page to distribute it; then delete.
        $items = $this->getRows();
        $id = $this->getCurrentPageId();
        $this->deletePage($id);

        $this->date = clone $this->getStartDate();
        $this->avoidHolidaysAndWeekdaysOff();
        $this->stats['start date'] = $this->date->format($this->getPageIdFormat());
        $this->stats['hours per day'] = $this->getHoursPerDay();
        $this->stats['total items'] = count($items);
        $this->stats['dates off'] = array();
        $this->setDatePage($this->date);

        $dayTotal = 0;
        $this->stats['total hours'] = 0;
        while (($item = array_shift($items))) {
            $this->stats['total hours'] += $item[$this->getHoursKey()];
            $this->processItem($item, $item[$this->getHoursKey()], $dayTotal);
        }
        $this->stats['end date'] = $this->date->format($this->getPageIdFormat());

        if ($this->todoStatsPage) {
            $this->addStatsPage($this->todoStatsPage);
        }

        return $this;
    }
603653
public function renew()
    {
        $hash = $this->getNewHash($this->Member());
        $this->Hash = $hash;
        $this->extend('onAfterRenewToken');
        $this->write();
        return $this;
    }
1373059
public function startOfWeek()
        {
            if ($this->dayOfWeek != self::MONDAY) $this->previous(self::MONDAY);

            return $this->startOfDay();
        }
873048
public function everyMinutes($minutes)
    {
        $minutesSchedule = self::ANY;
        if ($minutes != 1) {
            $minutesSchedule .= '/'.$minutes;
        }

        $this->setScheduleMinute($minutesSchedule);

        return $this;
    }