1

Is it possible to tell PHP to execute a piece of code on a given date and time? For example, Blogger.com allows someone to set a blogpost to be published in the future (e.g. 12/12/14 6:00AM).

Can PHP do something similar?

(Sorry, I don't even know what the correct term for events like these would be to be able to even search for them! :( )

j08691
  • 190,436
  • 28
  • 232
  • 252
Chuck Le Butt
  • 43,669
  • 58
  • 179
  • 268

5 Answers5

1

You can do this using a cron job (or scheduled task on Windows); although they are typically used for reoccurring jobs.

If you're using a database, most platforms come with a scheduler.

Kermit
  • 32,563
  • 10
  • 80
  • 117
1

You can schedule your action in your database and use a cronjob on your server or use a cron job service To run your actions.

https://www.setcronjob.com/

For example when you want to publish your blog in the future, you save your publish date in the future and set some sort of auto-publish bit.

Then every hour a PHP script is ran by a cronjob, this script checks the database for all blogs which need to be published.

Timmetje
  • 7,571
  • 16
  • 36
1

It's not possible to tell PHP to do this itself, since it would require a process to run forever to periodically call your PHP code. Thankfully though, there's a couple of things which do this:

1) Call a PHP script from a cron job, which then does any necessary work. If you don't have access to a crontab, you can periodically call this when a user pings your site instead, although that will be less reliable, of course.

2) Use at. This works in basically the same way as cron on Linux systems, but will schedule once and at an exact time.

slugonamission
  • 9,328
  • 29
  • 39
1

for "triggering code at a certain time", cron works. But for something as simple as publishing an article at a specific time, it isn't needed. You can just store a publish date with your article. When displaying a list of articles you can adjust your query to something like WHERE PUBLISH_DATE <= NOW() and on the article page check if the article's publish date has passed before showing the article.

Jonathan Kuhn
  • 14,619
  • 2
  • 28
  • 41
0

On Unix-like systems, there's Cron. You can manage Cron from PHP.

On Windows, there are scheduled tasks - you can also use PHP to manage scheduled tasks.

Be careful with this though - it's kinda hard to test, and you may end up with a schedule that cripples your server.

Community
  • 1
  • 1
Neville Kuyt
  • 27,150
  • 1
  • 34
  • 48