There are times that you want to run a java task periodically. In this case, you may consider using java timer class. The following is an example how you might use it. This example also demonstrate how to use java to send Http request.
import java.util.*;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class HttpRequest extends TimerTask {
String query_code;
HttpRequest (String query_code)
{
this.query_code = query_code;
}
@Override
public void run()
{
String request_url = "http://host/controller/method.html?q=" + query_code;
try
{
request_url = request_url.replaceAll(" ", "%20");
System.out.println("Sending request to " + request_url);
URL url = new URL(request_url);
InputStreamReader reader = new InputStreamReader(url.openStream());
BufferedReader in = new BufferedReader(reader);
String response;
while((response = in.readLine()) != null)
{
String[] temp = response.split(";");
for(String code : temp)
{
System.out.println(code);
}
}
in.close();
}
catch (Exception e)
{
System.err.println("Error posting request to " + request_url);
}
}
}
class Test {
public static main (String[] args)
{
HttpRequest request = new HttpRequest("query");
Timer request_timer = new Timer(true);
//0 means no delay, 5000 is the interval
request_timer.schedule(request, 0, 5000);
}
}
So you need to set up a class that extends TimerTask class. Do note that this class needs to override the method ‘run’. This is the method that actually being scheduled to run periodically. Then you need to create a Timer instance and use the schedule method to schedule a new task.
Read the rest of this entry »



