定时器任务

1、引入支持定时任务的jar包

<!-- 定时调度(定时任务) -->
<dependency>
	<groupId>quartz</groupId>
	<artifactId>quartz</artifactId>
	<version>1.5.2</version>
</dependency>

2、原生定时

@Test
public void time() throws Exception {
	// 定时器
	Timer timer = new Timer();
	// 开启定时任务(子线程)
	timer.schedule(new TimerTask() {
		@Override
		public void run() {
			System.out.println(new Date().toLocaleString());
		}
	}, 0, 1000);// 0:立即执行,1000:间隔1秒
	// 让主线程处于运行状态
	Thread.sleep(5000);
}

3、使用OpenSymphony Quartz 任务调度

点击进入【在线Cron表达式生成】

3.1 定时器的配置文件

<!--引入定时器配置-->
<import resource="classpath:applicationContext-timer.xml"/>

定时器配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

				http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">


    <!-- cron表达式:在每天早上8点到晚上8点期间每1分钟触发一次 -->
    <!--value>0 0/1 8-20 * * ?</value -->
    <!-- cron表达式:每5分钟触发一次 -->
    <!-- <value>0 0/5 * * * ?</value> -->

    <task:scheduled-tasks>
        <!-- 执行workService里面的work方法,执行频率是cron表达式 -->
        <!--每周每月每小时的50,51分每秒执行-->
        <task:scheduled ref="workService" method="work" cron="0 50,51 * * * ? " />
    </task:scheduled-tasks>
</beans>

3.2 效果

在这里插入图片描述

import com.yyw.aisell.service.IWorkServie;
import org.springframework.stereotype.Service;

@Service("workService") //自定义定时器配置的名字(不写默认就是类型首字母小写)
public class WorkServiceImpl implements IWorkServie {
    @Override
    public void work() {
        System.out.println("定时器执行");
    }
}

4、前端原生js实现定时器(附加)

<!--定时器按钮-->
<input type="button" value="开始" onclick="start()"/>
<input type="button" value="停止" onclick="stop()"/>

<!--定时器容器-->
<div id="showDate"></div>

<script type="text/javascript">
	var timer;
	function start(){
		//定时器方法,每过一秒就调用下面的方法执行一次展示时间
		timer = setInterval("startDate()",1000);
	}
	function startDate(){
		//创建当前时间
		var date = new Date();
		//将时间转换为正常格式
		date = date.toLocaleString();
		
		//将时间展示到定时器容器里面:每过一秒就调用一次这个方法得到的就是新的时间,实现定时器的原理
		document.getElementById("showDate").innerHTML=date;
	}
	
	//停止定时器
	function stop(){
		//调用周期定时器方法停止
		clearInterval(timer);
	}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值