Creating a Java timer and TimerTask?

I am new to Java and I am trying to set a simple timer, I am familiar with set_interval due to my experience with JavaScript and ActionScript,

I am not so familiar with the classes yet, so I am easily confused, I understand that I need to install a new Timer and then install TimerTask , but I don’t understand how to do this even if I am looking at the documentation right now.

So, I created an applet, and my init method:

 public void init() { TimerTask myTask; Timer myTimer; myTimer.schedule(myTask,5000); } 

How do I set the task code? I wanted him to do something like

 g.drawString("Display some text with changing variables here",10,10); 
+4
source share
4 answers

Whatever you do, for example, drawing or smwhat, just define the task and add code to it.

 import javax.swing.*; import java.awt.*; import java.util.Timer; import java.util.TimerTask; public class TimerApplet extends JApplet { String someText; int count = 0; public TimerApplet() { Timer time = new Timer(); alculate calculate = new alculate(); time.schedule(calculate, 1 * 1000, 1000); } class alculate extends TimerTask { @Override public void run() { count++; System.out.println("working.. "+count); someText = "Display some text with changing variables here.." +count; repaint(); } } //This is how do you actually code. @Override public void paint(Graphics g)//Paint method to display our message { // super.paint(g); flickering Graphics2D g2d = (Graphics2D)g; g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, getWidth(), getHeight()); if (someText != null) { g2d.setColor(Color.BLACK); g2d.drawString(someText,10,10); } //..... } } 
+2
source

As many great Stackoverflow users have said, the right idea here is to use javax.swing.TImer . Below is a small snippet of code for your help. Ask any question that is not understandable, I will also try to provide information.

 import java.awt.*; import java.awt.event.*; import java.util.Random; import javax.swing.*; public class DrawStringWithTimer { private final int WIDTH = 400; private final int HEIGHT = 300; private Timer timer; private int x; private int y; private int counter; private Random random; private String[] messages = { "Bingo, I am ON", "Can you believe this !!", "What else you thinking about ?", "Ahha, seems like you are confused now !!", "Lets Roll and Conquer :-)" }; private CustomPanel contentPane; private ActionListener timerAction = new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (counter == 5) counter = 0; /* * Creating random numbers where * x will be equal to zero or * less than WIDTH and y will be * equal to zero or less than HEIGHT. * And we getting the value of the * messages Array with counter variable * and passing this to setValues function, * so that it can trigger a repaint() * request, since the state of the * object has changed now. */ x = random.nextInt(WIDTH); y = random.nextInt(HEIGHT); contentPane.setValues(x, y, messages[counter]); counter++; } }; public DrawStringWithTimer() { counter = 0; x = y = 10; random = new Random(); } private void displayGUI() { JFrame frame = new JFrame("Drawing String Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); contentPane = new CustomPanel(WIDTH, HEIGHT); frame.setContentPane(contentPane); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); /* * javax.swing.Timer is what you need * when dealing with Timer related * task when using Swing. * For more info visit the link * as specified by @trashgod, in the * comments. * Two arguments to the constructor * specify as the delay and the * ActionListener associated with * this Timer Object. */ timer = new Timer(2000, timerAction); timer.start(); } public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new DrawStringWithTimer().displayGUI(); } }); } } class CustomPanel extends JPanel { private final int GAP = 10; private int width; private int height; private int x; private int y; private String message = ""; public CustomPanel(int w, int h) { width = w; height = h; setOpaque(true); setBackground(Color.WHITE); setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP)); } public void setValues(int x, int y, String msg) { this.x = x; this.y = y; message = msg; /* * As the state of the variables will change, * repaint() will call the paintComponent() * method indirectly by Swing itself. */ repaint(); } @Override public Dimension getPreferredSize() { return (new Dimension(width, height)); } @Override protected void paintComponent(Graphics g) { /* * Below line is used to draw the JPanel * in the usual Java way first. */ super.paintComponent(g); /* * This line is used to draw the dynamic * String at the given location. */ g.drawString(message, x, y); } } 
+2
source

An example, as you expected in this link

The timer will be started forever in our application until the application is closed or when the task or schedule is no longer available.

TimerTask is a task that has some functions that must be performed depending on time or duration.

In Timer, we will create a TimerTask to execute a specific duration or to start it to run at a specific duration.

Please understand how it works, apply with an applet or others.

1, the GCTask class extends the TimerTask class and implements the run () method.

2. In the TimerDemo program, a Timer object and a GCTask object are created.

3, using the Timer object, the task object is scheduled using the schedule () method of the Timer class to execute after a 5-second delay and then execute every 5 seconds.

4, an infinite while loop inside main () creates objects of type SimpleObject (the definition of which follows) that are immediately available for garbage collection.

 import java.util.TimerTask; public class GCTask extends TimerTask { public void run() { System.out.println("Running the scheduled task..."); System.gc(); } } import java.util.Timer; public class TimerDemo { public static void main(String [] args) { Timer timer = new Timer(); GCTask task = new GCTask(); timer.schedule(task, 5000, 5000); int counter = 1; while(true) { new SimpleObject("Object" + counter++); try { Thread.sleep(500); } catch(InterruptedException e) {} } } } public class SimpleObject { private String name; public SimpleObject(String n) { System.out.println("Instantiating " + n); name = n; } public void finalize() { System.out.println("*** " + name + " is getting garbage collected ***"); } } 
+1
source

I figured out the same problem in my small application, I know that my solution is not the best, but it is simple. just use two custom options in your custom inner class. here is my code.

 final static Random random = new Random(); ....//other codes static class MyTimerTask extends TimerTask { int index_x = random.nextInt(50); int index_y = random.nextInt(50); @Override public void run() { System.out.println("Display some text with changing variables here: " + index_x + "," + index_y); index_x = random.nextInt(50); index_y = random.nextInt(50); System.gc(); } public static MyTimerTask getInstance() { return new MyTimerTask(); } } 
+1
source

Source: https://habr.com/ru/post/1443637/


All Articles