Jump to content

simple lazy cron from template not working


Recommended Posts

I have a template called cronjobs.php. All it has (for now) is this super simple laze cron cal that attempts to write an entry to a processwire log file:

function cronTest(HookEvent $e) {

    wire('log')->save("cronjobs", "Cronjobs executed.");


// add a hook to your function:
wire()->addHook('LazyCron::every30Seconds', null, 'cronTest');

This does not work (no entry is ever added to the 'cronjobs' log file (despite me refreshing the page with the cronjobs.php template a hundred times). 

Am I doing something wrong?

Link to comment
Share on other sites

Your code cannot work. Your template is loaded after initialization of LazyCron. You have either to put your function in an autoload module or to initialize LazyCron again.

function cronTest(HookEvent $e) {     
  wire('log')->save("cronjobs", "Cronjobs executed.");     
wire()->addHook('LazyCron::every30Seconds', null, 'cronTest');
// $modules->get('LazyCron')->init();

I have to correct myself! Lazycron adds a hook in ProcessPageView::finished which is executed after the template is loaded. Sorry for confusing.
I tried your code and it works here. Beside caching missing write permission (assets/logs/) could cause the problem.

Edited by kixe
Link to comment
Share on other sites

Thanks for the suggestions guys, but it turned out not to be a cache or permission problem: I had set the page to 'unpublished' because I want nobody but an automated cron job to use that page. Publishing the page enables lazy cron to start working.

Edit: it worked a few times (as in the log was updated with a few new entries), but now it stopped working. Refreshing the page with the cronjobs.php template does absolutely nothing as far as the lazy cron is concerned  :( If I write to the log file directly in this template, it works just fine, for example wire('log')->save("cronjobs", "Cronjobs template executed.");

Edit 2: the cron started working again after I put some extra output in the cronjobs.php template. So it seems like if there is no output in a template (e.g. echo "hi"), the template file won't be processed. This is in the default PW multilanguage setup (with _main.php and _init.php automatically prepended to templates).

Link to comment
Share on other sites

  • 2 months later...

Just thought I'd add the solution to this problem, for reference. Turns out there's a file called /site/assets/cache/LazyCron.lock (or something along those lines) preventing the cron functionality from working when there are PHP errors in my cron logic, which can happen during development of course. Fixing the errors and deleting the lock file restores functionality. 

  • Like 8
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Similar Content

    • By benbyf
      Hello, having trouble getting PW to save my user or field in cron hook.
      It seems to report the same field info each time unchanged. It should be counting down in seconds.
      public function init() { // set to every30Seconds in settings $this->defaultInterval = $this->cron_check; // add hooks to CRON $this->addHookAfter("LazyCron::{$this->defaultInterval}", $this, 'checkUserSubscription'); } public function ___checkUserSubscription(HookEvent $e){ // seconds since last lazycron $seconds = $e->arguments[0]; $log = wire('log'); $field = $this->exclusiveRole; // users with specific role and field $users = $this->users->find("roles=$field"); foreach ($users as $user) { // get stored time $currentTime = $user->get($this->fieldName); // if time not null if($currentTime){ // evalute stored time minus time past $resultTime = intval($currentTime) - intval($seconds); $log->message("result ".$resultTime); // save user page $user->set($this->fieldName, $resultTime); $this->users->save($user); } } }  
    • By Anton Martin
      Hoping someone can assist me. I'm have an hourly cron job that runs a bootstrapped script in my public_html folder but it is failing with the following error.
      <b>Notice</b>: Undefined index: argc in <b>/home/melbo111/public_html/wire/core/ProcessWire.php</b> on line <b>189</b><br /> The process used to run with the above error and still work but now on the live environment it doesn't work at all. Hopefully resolving this error will sort out my issues.
      Here is my cron script:
      0 * * * * /usr/bin/php -q /home/melbo111/public_html/abandon_cart.php And this is abandon_cart.php
      <?php include("index.php"); $timer = time() - 3600;//1hr ago $ab_orders = $wire->pages->find("template=order, payment_status=, order_date<$timer"); $flogo = "http://www.melbournechristmastrees.com/site/assets/files/1/logo.png";//$wire->pages->get(1)->logo->httpUrl; if(!empty($ab_orders)){ foreach($ab_orders as $ab_order){ if(isset($ab_order->stand) && $ab_order->stand === 1){ $stand = 'Yes'; }else { $stand = 'No'; } if(isset($ab_order->installation) && $ab_order->installation === 1){ $installation = 'Yes'; }else { $installation = 'No'; } if(isset($ab_order->removal) && $ab_order->removal === 1){ $removal = 'Yes'; }else { $removal = 'No'; } $colink = $wire->pages->get(1175)->httpUrl.'?acid='.$ab_order->id; $EmailTo = $ab_order->email; $subject ="Don't miss out on your Christmas tree"; $body = "<table width='600' align='center' border='0' cellpadding='0' cellspacing='0'> <tr> <td align='center' style='padding-top:10px; padding-bottom:20px;'> <img src='$flogo' height='80' alt='Melbourne Christmas Trees'> </td> </tr> <tr> <td><p>Dear $ab_order->shipping_first_name</p> <p>We noticed your shopping cart at Melbourne Christmas Trees has been reserved and is waiting for you.</p> In your cart you left: <ul> <li>$ab_order->product_ordered</li> <li>Stand: $stand </li> <li>Installation: $installation</li> <li>Removal: $removal</li> </ul> To complete your purchase, click the below link: <p style='text-align:center; padding-bottom:40px;'><a href='$colink' style='padding-top:10px; color:#fd2864; font-weight:bold;'>Complete Your Purchase</a></p> </td> </tr> <tr> <td style='padding-top:20px; padding-bottom:20px;'> <p style='color:#82b849; font-size:18px; text-align:center;'><strong>Have a fantastic Christmas from Melbourne Christmas Trees. </td> </tr> </table>"; $headers = 'MIME-Version: 1.0'."\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n"; $headers .= "From: Melbourne Christmas Trees <{$wire->users->get('xxxx')->email}>"."\r\n"; mail($EmailTo, $subject, $body, $headers); $ab_order->of(false); $ab_order->payment_status = "emailed_abandoned_cart"; $ab_order->save(); $wire->log->save('ac_emails', 'Order ID: '.$ab_order->id); $hazrun = true; } } echo "abandon process"; ?> I'm not a real coder and have hacked together so any general feedback on my code is also appreciated.
    • By hellomoto
      Would anyone here be able and inspired to develop a ProcessWire equivalent to the WordPress plugin WP All Import Pro? or to help me do so?
      This is what I'm envisioning...
      Upon installation the module creates an admin page titled "Import & Update". On the module config page you can specify allowed templates to run this on, otherwise allowing any. Include the following PHP libraries: hQuery for web scraping, Csv for CSV handling, and Parser for XML. Create template "import-update". On the "Import & Update" page, a list of current import/updaters will be displayed (0 initially), each with corresponding links to "edit" or "run". When you "Add New", this be the "import-update" template (with all module-specific fields tagged "impupd"):
      title destination (req.): parent, template source (req.): type (web, csv, xml) location (url, file, text) if web: opt. index URL & link selector, + paginator selector if csv: opt. ignore 1st row if xml: req. individual item node xpath actions (check): import (if none matching UID) update (if matching UID & field values differ) save() [req. here in flow] map (repeater): input (select fields from specified template to affect) intake (corresponding DOM selectors / CSV col. letters/headers / xpath per field) (req.) UID (unique ID; field reference to compare against, from selected input fields) (req.) Lazy Cron interval Scripts can be run via the import-update template; keep logs; show preview (iframe/ajax) for manual runs. ...
    • By Vineet Sawant
      I've been reading about Cron & Lazy Cron for days, but since my knowledge of programming is fairly limited, I couldn't get a single task done, so I'm here again to seek some help, probably learn a thing or two.
      Firstly, Cron is task scheduler run by the server, right?  And lazy cron is run by ProcessWire which runs only when page is loaded??
      If lazy cron runs only when pages are loaded, how will it run periodically?
      My requirement is, on every first minute of a day, a specific page(which will contain some code to perform several tasks) should run.
      Since right now,  the code doesn't need any specific time to run, I just run the page manually every morning. But there will be a time when it'll need to run at very specific time.
      I wish to know if this requirement can be fulfilled by Lazy Cron or will I also need to use cron?
      I wish to know what's the difference between Lazy Cron  & CRON? And when to use which?
      Also, I need to run a PW page specifically a minute after every midnight. Will it possible only with Lazy Cron or will I have to use Cron as well?
      For running URL instead of file in CRON, I'm looking at this solution by Horst.
    • By Biorn
      Hi guys..
      Long time no see...
      Well, Im back to some web programming again, I have been on tour with a Odense symphony orchestra..
      Ok, I havent played with cron or lazycron before, so I was wondering, can it be used to auto refresh a website?
      I startet a digital signage project, where Im planning to use processwire as the core, and then I need it to refresh or update the player browser every day at midnight, and maybe doing the day, when some of the items are done..
      Hope you can give me an answer...
        // Biorn
  • Create New...