我很困惑如何创建后台线程来运行某个功能。我有一个函数readRSS()从互联网上读取RSS,但是加载它需要很长时间,所以我想知道如何创建一个线程来每隔几个小时执行一次这个函数,同时我的程序的视觉效果运行。代码如下所示。
int n;
float[][] points;
float lat, lon, r, t;
PVector coord;
PShape globe;
PImage earth_texture;
void setup() {
size(1800, 1800, P3D);
coord = new PVector();
background(0);
n = 25; // number of points
r = 600; // sphere's radius
t = 0; // rotation accumulator
readRSS();
populateGlobe();
createGlobe();
}
void draw() {
background(0);
translate(width/2, height/2); //centers earth
rotateY(6 * radians(t += (TWO_PI / 365)));//change this to change speed of
rotation
shape(globe);
//points
fill(255,0,0);
stroke(255,0,0);
strokeWeight(12);
for (int i=1; i<points.length; i++) {
//cartesian coordinate conversion
lat = radians(points[i][0]);
lon = radians(points[i][1]);
coord.x = r * cos(lat) * cos(lon);
coord.y = r * cos(lat) * sin(lon);
coord.z = r * sin(lat);
point(coord.x, coord.y, coord.z);
}
}
//creates globe and sets texture
void createGlobe(){
//sets texture
noStroke();
earth_texture = loadImage("earthmap2.jpg");
globe = createShape(SPHERE, r);
globe.setTexture(earth_texture);
}
void populateGlobe(){
// populate globe w/ random GPS coordinates
points = new float[n][2];
for (int i=0; i<points.length; i++) {
points[i][0] = random(-90, 90); // latitude
points[i][1] = random(-180, 180); // longitude
}
}
//this prints RSS to console
void readRSS(){
XML rss = loadXML("https://it.einnews.com/rss/Ds5YG_pF3PymkwhH");
XML[] news = rss.getChildren("channel/item");
for(XML it : news){
XML header = it.getChild("title");
println(header.getContent());
}
}
答案 0 :(得分:0)
通过查看the reference可以最好地回答这些问题。具体来说,听起来你正在寻找thread()
功能。
String time = "";
void setup() {
size(100, 100);
}
void draw() {
background(0);
// Every 30 frames request new data
if (frameCount % 30 == 0) {
thread("requestData");
}
text(time, 10, 50);
}
// This happens as a separate thread and can take as long as it wants
void requestData() {
JSONObject json = loadJSONObject("http://time.jsontest.com/");
time = json.getString("time");
}