alyx
alyx

Reputation: 2733

Python: Auto refresh local PHP file

I am trying to execute a basic script on my server to automatically run a PHP script every 45 seconds through Python:

import os
import time

while(1):                                              
    os.spawnl(os.P_NOWAIT, "twitter_clean.php")
    print "checked twitter"
    time.sleep(45)

The PHP is checking twitter, processing some values and adding them to a DB. The script seems to loop fine, but doesn't seem to be calling/executing the PHP...is os.spawnl(os.P_NOWAIT, "twitter_clean.php") the right command?

Also, once I execute the Python through terminal, will it keep running if I close my SSH session with the server?

Upvotes: 0

Views: 639

Answers (4)

aurora
aurora

Reputation: 9627

You could try to solve this with PHP only. Have a look at the "tick" functionality:

http://de.php.net/manual/en/function.register-tick-function.php

http://de.php.net/manual/en/control-structures.declare.php#control-structures.declare.ticks

You could register a tick function. You could write the code about to only execute the function every 45 seconds within the registered function. I think this would be much more easy and you could also implement a functionality much more easy which would prevent executing the function multiple times (if 45 seconds is not enough for executing it).

Than you can use the command "nohup" to start the script as "background"-job easy.

Upvotes: 0

Havenless
Havenless

Reputation: 116

To leave it running after you close the session use nohup, but if this is anything more than a temporary situation, you'll need to use cron to call the php (as Jeff Day says) or start the Python automatically, try looking at: man chkconfig

Upvotes: 1

0xd
0xd

Reputation: 1901

You should call PHP-Cli passing that file as parameter

import os
import time

while(1):                                              
    os.spawnl(os.P_NOWAIT, "/path/to/php-cli twitter_clean.php")
    print "checked twitter"
    time.sleep(45)

And to keep it running, try to make it an Daemon: How do you create a daemon in Python?

Upvotes: 2

Jeff Day
Jeff Day

Reputation: 3717

Why not just use crontab for this? Getting it to run every 45 seconds is a little harder, but if you're willing to go to either 1 minute or 30 seconds you should be able to do this much more simply than using a python script.

Upvotes: 1

Related Questions