问题
I'm trying to put in a check for Phirehose to stop running after 10 seconds or 100 tweets...basically, I want to be able to stop the script.
I was told I could customize the statusUpdate()
function or the heartBeat()
function, but I'm uncertain how to do that. Right now, I'm just testing with the filter-track.php
example.
How do I customize the functions, and where should I call them in the class?
class FilterTrackConsumer extends OauthPhirehose
{
/**
* Enqueue each status
*
* @param string $status
*/
public function enqueueStatus($status)
{
/*
* In this simple example, we will just display to STDOUT rather than enqueue.
* NOTE: You should NOT be processing tweets at this point in a real application, instead they should be being
* enqueued and processed asyncronously from the collection process.
*/
$data = json_decode($status, true);
if (is_array($data) && isset($data['user']['screen_name'])) {
print $data['user']['screen_name'] . ': ' . urldecode($data['text']) . "\n";
}
}
public function statusUpdate()
{
return "asdf";
}
}
// The OAuth credentials you received when registering your app at Twitter
define("TWITTER_CONSUMER_KEY", "");
define("TWITTER_CONSUMER_SECRET", "");
// The OAuth data for the twitter account
define("OAUTH_TOKEN", "");
define("OAUTH_SECRET", "");
// Start streaming
$sc = new FilterTrackConsumer(OAUTH_TOKEN, OAUTH_SECRET, Phirehose::METHOD_FILTER);
$sc->setLang('en');
$sc->setTrack(array('love'));
$sc->consume();
回答1:
To stop after 100 tweets, have a counter in that function receiving the tweets, and call exit when done:
class FilterTrackConsumer extends OauthPhirehose
{
private $tweetCount = 0;
public function enqueueStatus($status)
{
//Process $status here
if(++$this->tweetCount >= 100)exit;
}
...
(Instead of exit
you could throw an exception, and put a try/catch around your $sc->consume();
line.)
For shutdown "after 10 seconds", this is easy if it can be roughly 10 seconds (i.e. put a time check in enqueueStatus()
, and exit if it has been more than 10 seconds since the program started), but hard if you want it to be exactly 10 seconds. This is because enqueueStatus()
is only called when a tweet comes in. So, as an extreme example, if you get 200 tweets in the first 9 seconds, but then it goes quiet and the 201st tweet does not arrive for 80 more seconds, your program would not exit until the program has been running 89 seconds.
Taking a step back, wanting to stop Phirehose is normally a sign it is the wrong tool for the job. If you just want to poll 100 recent tweets, every now and again, then the REST API, doing a simple search, is better. The streaming API is more for applications that intend to run 24/7, and want to react to tweets as soon as they are, well, tweeted. (More critically, Twitter will rate-limit, or close, your account if you connect too frequently.)
来源:https://stackoverflow.com/questions/30876738/how-do-i-customize-and-use-phirehose-functions