几种定时器介绍

1:java定时器的几种用法

  1. package com.lid;  
  2.   
  3. import java.util.Calendar;  
  4. import java.util.Date;  
  5. import java.util.Timer;  
  6. import java.util.TimerTask;  
  7.   
  8. public class Test {  
  9.     public static void main(String[] args) {  
  10.         //timer1();  
  11.         timer2();  
  12.         //timer3();  
  13.         //timer4();  
  14.     }  
  15.   
  16.     // 第一种方法:设定指定任务task在指定时间time执行 schedule(TimerTask task, Date time)  
  17.     public static void timer1() {  
  18.         Timer timer = new Timer();  
  19.         timer.schedule(new TimerTask() {  
  20.             public void run() {  
  21.                 System.out.println("-------设定要指定任务--------");  
  22.             }  
  23.         }, 2000);// 设定指定的时间time,此处为2000毫秒  
  24.     }  
  25.   
  26.     // 第二种方法:设定指定任务task在指定延迟delay后进行固定延迟peroid的执行  
  27.     // schedule(TimerTask task, long delay, long period)  
  28.     public static void timer2() {  
  29.         Timer timer = new Timer();  
  30.         timer.schedule(new TimerTask() {  
  31.             public void run() {  
  32.                 System.out.println("-------设定要指定任务--------");  
  33.             }  
  34.         }, 10001000);  
  35.     }  
  36.   
  37.     // 第三种方法:设定指定任务task在指定延迟delay后进行固定频率peroid的执行。  
  38.     // scheduleAtFixedRate(TimerTask task, long delay, long period)  
  39.     public static void timer3() {  
  40.         Timer timer = new Timer();  
  41.         timer.scheduleAtFixedRate(new TimerTask() {  
  42.             public void run() {  
  43.                 System.out.println("-------设定要指定任务--------");  
  44.             }  
  45.         }, 10002000);  
  46.     }  
  47.      
  48.     // 第四种方法:安排指定的任务task在指定的时间firstTime开始进行重复的固定速率period执行.  
  49.     // Timer.scheduleAtFixedRate(TimerTask task,Date firstTime,long period)  
  50.     public static void timer4() {  
  51.         Calendar calendar = Calendar.getInstance();  
  52.         calendar.set(Calendar.HOUR_OF_DAY, 12); // 控制时  
  53.         calendar.set(Calendar.MINUTE, 0);       // 控制分  
  54.         calendar.set(Calendar.SECOND, 0);       // 控制秒  
  55.   
  56.         Date time = calendar.getTime();         // 得出执行任务的时间,此处为今天的12:00:00  
  57.   
  58.         Timer timer = new Timer();  
  59.         timer.scheduleAtFixedRate(new TimerTask() {  
  60.             public void run() {  
  61.                 System.out.println("-------设定要指定任务--------");  
  62.             }  
  63.         }, time, 1000 * 60 * 60 * 24);// 这里设定将延时每天固定执行  
  64.     }  
  65. }  

2:spring中定时器的使用

 

在Spring中有两种方式可以实现定时器的功能,分别是Scheduled注释方式和XML配置方式,本博客将介绍如何在Spring中使用Scheduled注释方式的方式实现定时器的功能,代码及相应的解释如下:

代码1—Spring配置文件(applicationContext.xml文件):

 

 

 

<beans beans="" context="" http:="" schema="" spring-beans-2.5.xsd="" spring-context-2.5.xsd="" spring-task-3.2.xsd="" task="" www.springframework.org=""
xmlns=" http://www.springframework.org/schema/beans"
xmlns:context=" http://www.springframework.org/schema/context"
xmlns:task=" http://www.springframework.org/schema/task"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation=" http://www.springframework.org/schema/beans">
  <context:annotation-config>
    <context:component-scan base-package="com.ghj/">
      <task:executor id="executor" pool-size="5">
        <task:scheduler id="scheduler" pool-size="10">
           <task:annotation-driven executor="executor" scheduler="scheduler">
           </task:annotation-driven>
        </task:scheduler>
      </task:executor>
    </context:component-scan>
  </context:annotation-config>
</beans>

 

 

代码2——Spring定时器测试类(SpringTimerTest.java文件):

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.ghj.packageoftimer;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
/**
  * Spring定时器测试类
  *
  * @author 高焕杰
  */
@Component //将本类完成bean创建和自动依赖注入
public class SpringTimerTest{
     
     /**
      * Spring定时器测试方法
      *
      * @author 高焕杰
      */
     @Scheduled (cron = 0 0 / 1 * * * ?) //通过@Scheduled注释将该方法定义为Spring定时调用的方法,其中cron用于指明该方法被调用的时机
     public void test(){
         System.err.println( new SimpleDateFormat(yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒).format( new Date()));
     }
}

 

代码3——加载Spring配置文件并启动Spring定时器的类(StartSpringTimer.java文件):

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.ghj.packageoftest;
 
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
/**
  * 加载Spring配置文件,启动Spring定时器
  *
  * @author 高焕杰
  */
public class StartSpringTimer {
 
     public static void main(String[] args){
         new ClassPathXmlApplicationContext(conf/spring/applicationContext.xml);
         System.out.println(加载Spring配置文件完毕,Spring定时器成功启动!!!);
     }
}

 

这种方式实现Spring定时器的优点:

采用这种方式实现定时器的功能是我最喜欢的,这种方式简单灵活——只要在已被加载到Spring容器中的类内的方法上添加Scheduled注释并指定该方法的时机即可。

答疑解惑:

如果你是有心人,你可能会有这样的疑惑加载中...:在采用这种方式实现的Spring定时器时被Scheduled注释的方法的访问权限有没有特别的要求,呵呵呵加载中...,这是没有什么特别的要求的,你完全可以把该方法定义为私有的,这样就不会把该方法暴漏出去了。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C# 中,你可以使用以下几种方法来实现定时器功能: 1. System.Timers.Timer:这是一个基于线程的定时器,可以在指定的时间间隔内重复执行指定的代码。你可以设置 Interval 属性来指定时间间隔,并通过 Elapsed 事件来处理计时器事件。 ```csharp using System; using System.Timers; public class TimerExample { private static Timer timer; public static void Main() { timer = new Timer(); timer.Interval = 1000; // 设置时间间隔为1秒 timer.Elapsed += TimerElapsed; // 绑定事件处理程序 timer.Enabled = true; // 启动计时器 Console.WriteLine("Press Enter to stop the timer."); Console.ReadLine(); timer.Enabled = false; // 停止计时器 } private static void TimerElapsed(object sender, ElapsedEventArgs e) { Console.WriteLine("Timer elapsed at {0}", e.SignalTime); } } ``` 2. System.Threading.Timer:这是一个基于线程池的定时器,也可以在指定的时间间隔内重复执行指定的代码。你可以使用 Change 方法来设置时间间隔,并通过 TimerCallback 委托来处理计时器事件。 ```csharp using System; using System.Threading; public class TimerExample { private static Timer timer; public static void Main() { TimerCallback callback = new TimerCallback(TimerElapsed); timer = new Timer(callback, null, 0, 1000); // 设置时间间隔为1秒 Console.WriteLine("Press Enter to stop the timer."); Console.ReadLine(); timer.Dispose(); // 停止计时器 } private static void TimerElapsed(object state) { Console.WriteLine("Timer elapsed at {0}", DateTime.Now); } } ``` 3. System.Threading.Tasks.Task.Delay:这是一种基于异步任务的延迟执行方法,可以在指定的时间间隔后执行指定的代码。 ```csharp using System; using System.Threading.Tasks; public class TimerExample { public static async Task Main() { Console.WriteLine("Press Enter to start the timer."); Console.ReadLine(); while (true) { Console.WriteLine("Timer elapsed at {0}", DateTime.Now); await Task.Delay(1000); // 设置时间间隔为1秒 } } } ``` 这些是在 C# 中实现定时器功能的几种常用方法。你可以根据自己的需求选择适合的方法来实现定时器功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值