I need to update the news feeds for every 5 minutes from a RSS feed .
I have written a TimerTask as shown below
public class TimerTaskForAllNews
{
public static void main( String[] args )
{
TimerTask task = new AllNewsUpdatrUtility();
Timer timer = new Timer();
timer.schedule(task, 1000,60000);
}
}
This is my TimerTask implementation class
package com.util;
import java.net.URL;
public class AllNewsUpdatrUtility extends TimerTask {
private static AllNewsUpdatrUtility instance = null;
public AllNewsUpdatrUtility() {}
public static AllNewsUpdatrUtility getInstance() {
if (instance == null)
instance = new AllNewsUpdatrUtility();
return instance;
}
@Override
public void run() {
try {
JSONArray latestnews = new JSONArray();
JSONObject jsonobj_allnews = new JSONObject();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL url = new URL("http://www.rssmix.com/u/8160628/rss.xml");
Document doc = builder.parse(url.openStream());
NodeList items = doc.getElementsByTagName("item");
for (int i = 0; i < items.getLength(); i++) {
Element item = (Element) items.item(i);
String title = getValue(item, "title");
String link = getValue(item, "link");
String pub_date = getValue(item, "pubDate");
} // for loop ends here
} catch (Exception e) {
e.printStackTrace();
}
}
}
Could you please let me know i can improve this program anyway ?
The specification JSR 206 Java™ API for XML Processing (JAXP) 1.4 says:
It is expected that the newSAXParser method of a SAXParserFactory implementation, the newDocumentBuilder method of a DocumentBuilderFactory and the newTransformer method of a TransformerFactory will be thread safe without side effects.
As said in the comment you can cache the DocumentBuilderFactory instance :
package com.util;
import java.net.URL;
public class AllNewsUpdatrUtility extends TimerTask {
private static AllNewsUpdatrUtility instance;
private final DocumentBuilderFactory dbf;
private AllNewsUpdatrUtility() {}
public synchronized static AllNewsUpdatrUtility getInstance() {
if (instance == null)
instance = new AllNewsUpdatrUtility();
dbf = DocumentBuilderFactory.newInstance();
return instance;
}
@Override
public void run() {
try {
JSONArray latestnews = new JSONArray();
JSONObject jsonobj_allnews = new JSONObject();
DocumentBuilder builder = dbf.newDocumentBuilder();
URL url = new URL("http://www.rssmix.com/u/8160628/rss.xml");
Document doc = builder.parse(url.openStream());
NodeList items = doc.getElementsByTagName("item");
for (int i = 0; i < items.getLength(); i++) {
Element item = (Element) items.item(i);
String title = getValue(item, "title");
String link = getValue(item, "link");
String pub_date = getValue(item, "pubDate");
} // for loop ends here
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With