Arbiter
Arbiter

Reputation: 47

Storing a scripts last run time in PHP

I need to store the time of the last run of a script to make sure it doesn't read old items (tweets in this case). Whats the best way to keep track of this?

thanks.

Upvotes: 2

Views: 1669

Answers (5)

Mark Grey
Mark Grey

Reputation: 10257

Generate a timestamp and save it to a logfile that can be read on the next iteration.

$time_ran = time();

function saveTimeRan(){
  $fh = fopen('/path/to/a/new/log' 'w+');
  fwrite($fh, $time_ran);
  fclose($fh);
}

function getTimeRan(){
  $fh = fopen('/path/to/a/new/log' 'r+');
  $time = fgets($fh);
  fclose($fh);
  return $time;
}

Might I suggest you make this an object and put the contents of saveTimeRan in the magic __destruct function, so when your object is GC'ed it will save the time. Just a suggestion. You could put your tweet functions in other object methods and make one comprehensive interface. You could, alternatively, save the value to a database field and call it each iteration.

Upvotes: 2

Alfred
Alfred

Reputation: 61771

Whats the best way to keep track of this?

The best way is to keep track of that in memory(redis/apc/memcached/etc)(back upped by any persistent store(mysql/mongodb/redis/etc). You should try to avoid to touch the disc(I/O) because that's very very slow compared to speed of memory.

Redis

You can configure redis two ways:

  • write data back to persistent asynchronously(snapshotting) after certain time has passed and or keys have been modified.
  • write data back to persistent store immediately(append-only).

It's a trade-off(performance vs safety)

APC/Memcached

APC and Memcached don't have persistent storage so you have to do that using for example mysql.

Upvotes: 2

NightHawk
NightHawk

Reputation: 3681

You can have the script write a timestamp/date to a text file every time it runs. Then you can optionally read the file before running the script to make sure you don't run it again before x amount of time has passed or only run if a certain condition is true.

Check out file_put_contents and file_get_contents.

-Ryan

Upvotes: 0

gahooa
gahooa

Reputation: 137282

You gave zero information on specifics, so I will be general.

  1. Store it in a database like MySQL
  2. Write it to a local file with file_put_contents() and read it with file_get_contents()
  3. Touch a local file with one of the os functions, and then stat the file to see it's mtime
  4. Use sqlite to write it to a local database

Upvotes: 2

uadnal
uadnal

Reputation: 11435

You could store time stamps in a DB or a text file.

Upvotes: 0

Related Questions