Specific use of several timers of java 4 kinds of of

  • 2021-11-10 09:41:36
  • OfStack

Directory 1. @ Scheduled annotations
2.quartz
3. Use Timer
4. Use thread control

In summary 1, I have used four types of timers: @ Scheduled annotation, quartz, new Timer (). schedule, using thread control.

1. @ Scheduled annotations

The @ Scheduled annotation is the easiest way to do this is to enable the timer and add annotations to the method.

Add to the spring configuration:


<!--  Enable annotation timer  -->
 <task:annotation-driven />
 Add annotations to the specific methods @Scheduled

@Scheduled(cron = "0 0 * * * ? ")
    public void myTask(){
           // Timing task ......
}

2.quartz

quartz uses a configurable way to configure all timers in another xml file. The steps are as follows:

1. Create a configuration file for spring: spring-quartz. xml

2. job for defining work tasks

3. Define the trigger Trigger and bind it to job

4. Define the scheduler and register Trigger with scheduler


<bean id="myTask" class="cn.coolwind.MyTask"/>
 <!-- 1. Define work tasks job -->
    <bean id="testJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <!--  Class of timer   -->
        <property name="targetObject" ref="myTask"></property>
        <!--  Methods that need to be executed regularly   -->
        <property name="targetMethod" value="test"></property>
        <property name="concurrent" value="false"></property>
    </bean>
    <!-- 2. Define triggers Trigger And with Job Binding  -->
    <bean id="testJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="testJob"/>
        <!--  Set the timing execution time as needed  -->
        <property name="cronExpression" value="0 0/5 * * * ?" />
    </bean>
 
   <!-- 3. Define the scheduler and set the trigger Register in  -->
<bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                 <ref local="testJobTrigger" />
            </list>
        </property>
    </bean>

Finally, remember to write xml into web. xml!


    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
    classpath:applicationContext.xml,
    classpath:log4j.xml,
                classpath:spring-quartz.xml
   </param-value>
    </init-param>

3. Use Timer

schedule and schedule using Timer have three parameters:

schedule(TimerTask task, long delay, long period)
The first is a timed task, which can rewrite the run method of TimerTask according to business needs;

The second is delayed start, in milliseconds;

How often does the third bit run, in milliseconds;


new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    //do Something
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },0,5L * 60 * 1000);

4. Use thread control

Using threads to control is more flexible 1, you can judge when to run and when to stop according to your own needs, which requires a certain understanding of the threads of java.


public class TaskTest {
    private static final ExecutorService pool = Executors.newFixedThreadPool(5);//  Thread pool 
    public static final TaskTest me = new TaskTest();
    public final int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
 
    public static void main(String[] args) {
        me.start();
    }
 
    private void start() {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        for (int i = 0; i < arr.length; i++) {
                            if (1 == arr[i]) {
                                System.out.println("start!");
                                Thread.sleep(1*1000L);
                            }
                            if (6 == arr[i]) {
                                System.out.println("stop!");
                                Thread.sleep(5*1000L);
                            }
                            System.out.println(arr[i]);
                            if (9 == arr[i]) {
                                System.out.println("end!");
                                Thread.sleep(5*1000L);
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

Related articles: