Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a block of code in PHP once per day in main template file? Non cron

Tags:

php

cron

I have a block of PHP code that generates my sitemap.xml file. Problem is, it generates the file every time a site page is loaded. The code is in my main template file.

How could I tell PHP to only execute this code say, once per day, instead of every time the template is loaded?

I don't want to use cron tab because the code needs to be in the template file. The template file is pulled for multiple domains on the same account. So I need to put a condition on the block of code that says only run this code when a page is loaded but only during a certain time frame each day, like from 12 noon to 4pm or something like that.

I know that is what cron is for, but need it done in PHP.

UPDATE

So this is what I came up with based on Travesty3 answer.

$time  = time();
$sitemap = $_SERVER['DOCUMENT_ROOT'].'/sitemap.xml';
if ($time - filemtime($sitemap) >= 1*24*60*60) { // 1 days

(generate sitemap code here)

}

This works fine. The sitemap is now only being generated once per day only if the site has at least 1 visitor per day.

But if the site has a lot of traffic which was my original concern for doing this in the first place, won't checking the filemtime of the sitemap.xml file cause almost the same amount of overhead on the server as generating the sitemap file on each request?

like image 821
Mike Avatar asked Jan 30 '26 03:01

Mike


1 Answers

You could check the filemtime on the generated file and only generate it on page load if it's over 24 hours old.

Also, you can use cron to execute a PHP script or call a URL. So there's also that.

like image 128
Travesty3 Avatar answered Jan 31 '26 17:01

Travesty3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!