Reputation: 7
I am currently writing a java programm that fetches the source code from a html and parses it for a value. This works fine normally, but once I try to let it run in a while loop and refetch the data every 30 seconds my PC slows down until I stop the program manually.
while(true) {
try {
URL url = new URL("https://www.reddit.com/r/gaming/");
URLConnection urlConn = url.openConnection();
System.out.println(urlConn.getContentType()); //it returns text/html
BufferedReader in = new BufferedReader
(new InputStreamReader(urlConn.getInputStream()));
File test = new File("test");
BufferedWriter writer = new BufferedWriter(new FileWriter(test));
String text;
while ((text = in.readLine()) != null) {
writer.write (text);
}
writer.close();
in.close();
String content = new String(Files.readAllBytes(Paths.get("test")), "UTF-8");
Pattern pattern = Pattern.compile("title=(.*?)\">");
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
System.out.println(matcher.group(1));
if (Integer.valueOf((matcher.group(1))) <= 99999999) {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("alert.wav"));
clip.open(inputStream);
clip.start();
}
}
Thread.sleep(30000);
} catch (MalformedURLException f) {
f.printStackTrace();
} catch (IOException f) {
f.printStackTrace();
} catch (InterruptedException f) {
f.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
Any hints on why this is happening?
Upvotes: 0
Views: 77
Reputation: 26878
Maybe I'm misunderstanding the code, but I think that Thread.sleep()
will only run if you don't throw. I think you want to put it outside of the try/catch so that if you fail, you wait 30 seconds before trying again. Otherwise, if something causes a throw
, you will just retry again immediately and since nothing will have really changed since the last time you tried, you will immediately throw
again over and over.
Right now, your code is:
while (true) {
try {
// Do a lot of things that can throw
if(something_bad_happens) throw new Error();
/*
* This sleep will only be reached
* if we don't throw
*/
Thread.sleep(30000);
} catch (errors) {
// Deal with errors
}
}
I think you actually want this:
while (true) {
try {
// Do a lot of things that can throw
if(something_bad_happens) throw new Error();
} catch (errors) {
// Deal with errors
}
// Always sleep between attempts no matter what
Thread.sleep(30000);
}
Upvotes: 2