我试图使用java.util.timer定期安排任务;我不知道怎么做

时间:2016-05-22 17:53:51

标签: java arrays timer timertask

我已经研究了一段时间后在一定时间内安排任务的不同方法(例如Quartz,ScheduledThreadPool,java.util.timer),并且我在理解如何使用它时遇到了问题。

以下是我从研究中发现的一个例子,下面我将插入我正在创建的代码。 --->



ArticlePK artPK = new ArticlePK();

artPK.setId(12334);
artPK.setOrigin("ABC123");

Article article = em.find(Article.class, artPK);
System.out.printl("Article no: " + article.getArticleNo());




请忽略GUI App方法,我只是为了清楚而插入它。此外,我知道我的代码可能没有组织,所以我很抱歉提前。

所以基本上我已经创建了一个三帧的GUI;首先只是起始帧,因此可以忽略。第二帧是基本上将使用计时器的帧。我想要做的是创建一个记忆游戏,在12个JButton(我已经拥有)的数组中显示从1到12的12个随机数,然后在指定的时间后删除或隐藏(以较好者为准)数字和正在玩的人必须按升序点击它们。如果该人确实正确地点击了他们,他/她将得到1分,否则该人没有得分。他点击了#34;检查答案"按钮和数字重置,计时器再次启动。这只会发生15次。

为了清楚起见,我需要的所有帮助都是实现timer属性。感谢任何花时间阅读本文的人。你是一个救生员!



import java.util.Timer;
import java.util.TimerTask;

public class TaskManager {

    private Timer timer = new Timer();

    public static void main(String[] args) {
        TaskManager manager = new TaskManager();
        manager.startTask();
    }

    public void startTask() {
        timer.schedule(new PeriodicTask(), 0);
    }

    private class PeriodicTask extends TimerTask {
        @Override
        public void run() {
            System.out.println(System.currentTimeMillis() + " Running");

            /* replace with the actual task */
            try {
                Thread.sleep(15 * 1000);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            /* end task processing */

            System.out.println(System.currentTimeMillis() + " Scheduling 10 seconds from now");
            timer.schedule(new PeriodicTask(), 10 * 1000);
        }
    }
}




2 个答案:

答案 0 :(得分:0)

使用java.awt.event.ActionListener

import java.awt.event.*;
Timer t = new Timer(10, //will run every 10 ms
                    new Listener());
t.start();

private class Listener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e){
        //Code here will execute every (10) ms.
    }
}

答案 1 :(得分:0)

我认为存在一些混乱。 Timer类创建一个新的Thread,并将该线程上的任务运行到将来的指定时间或以指定的时间间隔重复运行该任务。以下代码描述了一个以两秒间隔移动红点的Swing类。 Thread.sleep方法使其包含的线程等待指定的时间段。 (睡眠可以被各种事件打断。)你第一次使用计时器实际上是假的,因为用于延迟的零意味着任务以零延迟运行。

您的PeriodicTask类打印一条消息,等待十五秒,打印一条消息,在10秒后安排重复该任务,然后退出。

package bradleyross.swing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.lang.reflect.InvocationTargetException;
import java.awt.event.KeyEvent;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
 * This Swing demo creates a JPanel component and randomly 
 * moves a red dot within the panel when triggered by a
 * timer.
 * 
 * @author Bradley Ross
 *
 */
public class SwingTimer implements Runnable{
    protected JFrame mainFrame;
    protected FlowLayout layout;
    protected MyPanel panel;
    protected int xPos = 0;
    protected int yPos = 0;
    protected Random random = new Random();
    protected Timer timer = new Timer();
    public void run() {
        buildFrame();
    }
    /**
     * Action listener for this application.
     * @author Bradley Ross
     *
     */
    protected class Listener1 implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            System.out.println("Action " + e.getActionCommand());
        }

    }
    /**
     * Key listener for this application.
     * @author Bradley Ross
     *
     */
    protected class Listener2 implements KeyListener {
        /** 
         * Action when key event is detected.
         *  @param e key event
         */
        public void keyTyped(KeyEvent e) {
            System.out.println("Keystroke received " + e.getKeyChar());
        }
        public void keyPressed(KeyEvent e) { ; }
        public void keyReleased(KeyEvent e) { ; }

    }
    /**
     * This subclass of JPanel repaints the
     * the dot using {@link SwingTimer#xPos} and 
     * {@link SwingTimer#yPos}.
     * 
     * @author Bradley Ross
     *
     */
    @SuppressWarnings("serial")
    public class MyPanel extends JPanel {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fillOval(xPos,  yPos, 5, 5);
        }
    }
    /**
     * Executed each time the timer triggers an event.
     * 
     * <p>It randomly repositions the dot within the
     *    panel.</p>
     * @author Bradley Ross
     *
     */
    public class Motion extends TimerTask {
        public void run() {
            xPos = random.nextInt(300);
            yPos = random.nextInt(300);
            panel.repaint();
        }
    }
    public void buildFrame() {
        xPos = random.nextInt(300);
        yPos = random.nextInt(300);
        KeyListener listener2 = new Listener2();
        ActionListener listener1 = new Listener1();
        mainFrame = new JFrame();
        layout = new FlowLayout(FlowLayout.LEADING);
        mainFrame.setLayout(layout);
        mainFrame.addKeyListener(listener2);
        JButton first = new JButton("First");
        first.setActionCommand("first");
        first.addActionListener(listener1);
        first.addKeyListener(listener2);
        first.setFocusable(false);
        mainFrame.add(first);
        mainFrame.setFocusable(true);
        panel = new MyPanel();
        panel.setBorder(BorderFactory.createLineBorder(Color.black));
        panel.setPreferredSize(new Dimension(300,300));
        panel.setForeground(Color.red);
        panel.addKeyListener(listener2);
        panel.repaint();
        timer.scheduleAtFixedRate(new Motion(), 0  , 2000);
        mainFrame.add(panel);
        mainFrame.setSize(500, 500);
        mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        mainFrame.setVisible(true);
    }
    /**
     * Main driver.
     * @param args not used in this example
     */
    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new SwingTimer());
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}