我在Processing中使用Twitter4j库来检索推文。我已经为我的应用程序添加了一个计时器,以便它以适当的间隔收集推文,而不会多次访问Twitter API。但是,我在实现Since_Id参数时遇到了麻烦,以便通过推文的时间轴前进(而不是像我现在那样向前)。如何跟踪MAX_ID,以便在计时器告诉我的应用程序再次运行时将值输入下一个间隔。
Timer timer;
import java.util.List;
void setup() {
timer = new Timer(30000);
timer.start();
goTwitter();
}
void draw(){
if (timer.isFinished()){
goTwitter();
timer.start();
}
}
void goTwitter(){
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("");
cb.setOAuthConsumerSecret("");
cb.setOAuthAccessToken("");
cb.setOAuthAccessTokenSecret("");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
Query query = new Query("#processing");
int numberOfTweets = 300;
long lastID = Long.MAX_VALUE;
ArrayList<Status> tweets = new ArrayList<Status>();
while (tweets.size () < numberOfTweets) {
if (numberOfTweets - tweets.size() > 100)
query.setCount(100);
else
query.setCount(numberOfTweets - tweets.size());
try {
QueryResult result = twitter.search(query);
tweets.addAll(result.getTweets());
println("Gathered " + tweets.size() + " tweets");
for (Status t: tweets)
if(t.getId() < lastID) lastID = t.getId();
}
catch (TwitterException te) {
println("Couldn't connect: " + te);
};
query.setMaxId(lastID-1);
}
for (int i = 0; i < tweets.size(); i++) {
Status t = (Status) tweets.get(i);
GeoLocation loc = t.getGeoLocation();
String user = t.getUser().getScreenName();
String msg = t.getText();
String time = "";
if (loc!=null) {
Double lat = t.getGeoLocation().getLatitude();
Double lon = t.getGeoLocation().getLongitude();
println(i + " USER: " + user + " wrote: " + msg + " located at " + lat + ", " + lon);
}
}
println("lastID= " + lastID);
}
class Timer {
int savedTime;
int totalTime;
Timer (int tempTotalTime) {
totalTime = tempTotalTime;
}
void start(){
savedTime = millis();
}
boolean isFinished() {
int passedTime = millis() - savedTime;
if (passedTime > totalTime){
return true;
} else {
return false;
}
}
}
答案 0 :(得分:1)
你可以走线
long lastID = Long.MAX_VALUE;
并将其移到
上方void setup() {
像这样:
long lastID = Long.MAX_VALUE;
void setup() {
基本上使它成为一个变量,可以通过Processing sketch中的每个方法访问,这是一种“全局变量”。此外,如果您希望它在每次达到推文数量后重新启动,您应该更改while循环中的else子句并使其像这样
else {
query.setCount(numberOfTweets - tweets.size());
long lastID = Long.MAX_VALUE;
}