「java定时每秒」java定时任务每秒执行一次
今天给各位分享java定时每秒的知识,其中也会对java定时任务每秒执行一次进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
java中如何实现自动计时功能,就是点击一个start按钮就开始计时,以秒为单位
简单代码如下:
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.Timer;
@SuppressWarnings("serial")
public class Timers extends JFrame {
final Label lab = new Label();
Date now = new Date();
@SuppressWarnings("deprecation")
public Timers() {
now.setHours(0);
now.setMinutes(0);
now.setSeconds(0);
setBounds(550, 270, 200, 150);
final Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
Date now2 = new Date(now.getTime() + 1000);
now = now2;
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
lab.setText(formatter.format(now));
}
});
Button b1 = new Button("开始");
Button b2 = new Button("停止");
b2.setBounds(40, 40, 40, 40);
b1.setBounds(30, 30, 30, 30);
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Button b = (Button) e.getSource();
b.setLabel("开始");
timer.start();
}
});
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Button b = (Button) e.getSource();
b.setLabel("停止");
timer.stop();
}
});
this.setLayout(new FlowLayout());
this.add(b2);
this.add(b1);
this.add(lab);
this.setSize(300, 200);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Timers t = new Timers();
t.lab.setText("00:00:00");
}
}
不知是否帮到你,如满意请采纳!
关于java定时任务
第一种方法是写一个线程,每秒运行一次,检测当前系统时间,如果是0时0分0秒,那么就把count设为1
第二种方法是用quartz框架,进行调度,调度规则是每天0点整运行一次,运行的内容就是把count设为1
用java编写一个定时器每隔一秒钟,在控制台打印出
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println("0");
}
}, 0, 1000);
java定时每秒的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java定时任务每秒执行一次、java定时每秒的信息别忘了在本站进行查找喔。