Milos
Milos

Reputation: 677

Create Magento cron job task programmatically

I want to create cron job task programmatically without using config.xml file. Is it possible?

Upvotes: 6

Views: 4785

Answers (3)

sureshc
sureshc

Reputation: 1

Use the below code to fix the issue.

use Magento\Cron\Model\ScheduleFactory;

$jobCode = 'jobcode';

$schedule = $this->scheduleFactory->create();

$schedule->setJobCode($jobCode) ->setCreatedAt($timecreated) ->setScheduledAt($timescheduled) ->setStatus(self::STATUS_PENDING)->save();

Upvotes: 0

Milos
Milos

Reputation: 677

I found the solution at: http://www.ayasoftware.com/how-create-cron-jobs-dynamically-magento

$timecreated   = strftime("%Y-%m-%d %H:%M:%S",  mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y")));
$timescheduled = strftime("%Y-%m-%d %H:%M:%S", mktime(date("H"), date("i")+ 5, date("s"), date("m"), date("d"), date("Y")));
$jobCode = 'job_id';

try {
    $schedule = Mage::getModel('cron/schedule');
     $schedule->setJobCode($jobCode)
        ->setCreatedAt($timecreated)
        ->setScheduledAt($timescheduled)
        ->setStatus(Mage_Cron_Model_Schedule::STATUS_PENDING)
        ->save();
   } catch (Exception $e) {
     throw new Exception(Mage::helper('cron')->__('Unable to save Cron expression'));
   }

Upvotes: 6

Christophe Ferreboeuf
Christophe Ferreboeuf

Reputation: 1058

I do not see what is the purpose of that and there is probably a better way to do but I think it should be done like that

I never had this case but you probably can use the class Mage_Cron_Model_Schedule Mage::getModel('cron/schedule') and set data accordingly, then save. You need to define what is the cron task anyway in a config.xml for magento to be able to associate.

It should populate the table cron_schedule that it is checked for the cron tasks to be ran.

Upvotes: 2

Related Questions