So I would like to make a program which opens the "Never Gonna Give You Up" every n-seconds. For this I implemented a Timer. Since I dont have alot of experience, It doesnt work (No output and finishes instantly with exit code 0).
Thanks in advance
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
public class Rickroll implements ActionListener {
public static void main(String[] args) {
Rickroll r = new Rickroll();
r.startTimer();
}
public void startTimer()
{
new Timer(2000, this).start();
}
@Override
public void actionPerformed(ActionEvent e)
{
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URL("https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstleyVEVO").toURI());
} catch (URISyntaxException | IOException i) {
System.exit(1);
}
}
}
What you are using is a javax.swing.Timer
, which should be used to update and/or change Swing-components, meaning they should not be used in this instance.
You could however use a java.util.Timer
, or a ScheduledExecutorService
to perform this task. While Timer
are easier to understand, a ScheduledExecutorService
gives you more freedom in scheduling tasks. AFAIK, ScheduledExecutorService
s are more resilient to Runtime Exception
s, so there's another upside to using them.
The implementation of both would look like this:
java.util.Timer
:
import java.awt.Desktop;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
public class Rickroll {
private static Desktop desktop = Desktop.getDesktop();
public static void main(String[] args) {
int n = 10;
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
openVideo();
}
}, 0, n * 1000);
}
private static void openVideo() {
try {
desktop.browse(new URL("https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstleyVEVO").toURI());
} catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
}
ScheduledExecutorService
:
import java.awt.Desktop;
import java.net.URL;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Rickroll {
private static Desktop desktop = Desktop.getDesktop();
public static void main(String[] args) {
int n = 10;
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
service.scheduleAtFixedRate(() -> openVideo(), 0, n, TimeUnit.SECONDS);
}
private static void openVideo() {
try {
desktop.browse(new URL("https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstleyVEVO").toURI());
} catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
}