Java中定时器的一些使用

目录

Thread

ScheduledExecutorService

Timer与TimerTask

Quartz


Thread

创建一个thread,然后让他一直在while循环中一直运行中,通过sleep方法达到定时任务的效果。

public class ThreadForAtFixedTime {
	
	public static void main(String[] args) {
		
		final long timeInterval = 1000*60;
		
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				
				while(true){
					
					System.out.println("say Hello World");
					
					try {
						Thread.sleep(timeInterval);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				
				
			}
		};
		
		Thread thread = new Thread(runnable);
		
		thread.start();
		
	}

}

ScheduledExecutorService

(1) 

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,

                                                  long initialDelay,

                                                  long period,

                                                  TimeUnit unit);

command表示执行线程,initialDelay表示初始化延时,period表示两次开始执行最小时间间隔,unit表示计时单位。

(2)

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,

                                                     long initialDelay,

                                                     long delay,

                                                     TimeUnit unit);

command表示执行线程,initialDelay表示初始化延时,period表示前一次执行结束到下一次执行开始的间隔时间(间隔执行延时时间),unit表示计时单位。

public class TestFixedTask implements InitializingBean{
	
	private ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
	
	@Autowired
	private ConfigPath config;

	@Override
	public void afterPropertiesSet() throws Exception {
		
		long oneDay = 1000 * 60 * 60 * 24;
		//获取配置的定时任务的时间(此处涉及到项目信息,注释掉)
		String dataString = "";
		
		long initDelay = 0;
		
		if(StringUtils.isNotBlank(dataString)){
			
			initDelay = getTimeMillis(dataString) - System.currentTimeMillis();
			
		}else{
			
			initDelay = getTimeMillis("00:30:00") - System.currentTimeMillis();
		}
		//如果是大于0,则在当天执行,否则的话,就在明天同一时间执行。
		initDelay = initDelay > 0 ? initDelay : initDelay + oneDay;
		
		scheduledExecutor.scheduleAtFixedRate(new Runnable() {
			
			public void run() {
				//部署多台服务器时的URL:http://ip1:port/project/request,http://ip2:port/project/request
				String url = config.databaserunning_batch_url;
				//本台服务器配置的URL:http://ip1:port/project/request
				String selfUrl = config.self_url;
				
				String[] urls = url.split(",");
				
				for(int i=0;i<urls.length;i++){
					
					if(urls[i].equalsIgnoreCase(selfUrl)){
						
						//得到请求的主机和端口号
						String host = urls[i].split("\\:")[1].replace("//", "");
						
						String port = urls[i].split("\\:")[2].substring(0, urls[i].split("\\:")[2].indexOf("/"));
						//判断目标地址是否ok
						boolean hostConnectable = CheckWebService.isHostConnectable(host, Integer.parseInt(port));
						
						if(hostConnectable){
							
							log.info("execute ip:"+host+",port:"+port);
							//执行指定的任务
							insertSelectResultToTransactionBean();
							
							break;
						}
						
					}else{
						//得到请求的主机和端口号
						String host = urls[i].split("\\:")[1].replace("//", "");
						
						String port = urls[i].split("\\:")[2].substring(0, urls[i].split("\\:")[2].indexOf("/"));
						//判断目标地址是否ok
						boolean hostConnectable = CheckWebService.isHostConnectable(host, Integer.parseInt(port));
						
						if(hostConnectable){
							
							break;
							
						}else{
							
							continue;
							
						}	
						
					}
				
				}
				
			}
		}, initDelay, oneDay, TimeUnit.MILLISECONDS);
	}
	
	private long getTimeMillis(String time) {

		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");

		try {

			Date date = format1.parse(format2.format(new Date()) + " " + time);

			return date.getTime();

		} catch (ParseException e) {

			e.printStackTrace();
		}

		return 0;
	}

}
@Component
public class ConfigPath {

	@Value("${databaserunning_batch_url}")
	public String databaserunning_batch_url = "";
	
	@Value("${self_url}")
	public String self_url = "";

}
self_url=http://ip1:port/project/request
databaserunning_batch_url=http://ip1:port/project/request,http://ip2:port/project/request
package com.eastrobot.robotdev.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;

public class CheckWebService {
	
	public static String getWSStatus1(String path){
		
		try {
			URL url = new URL(path);
			
			HttpURLConnection httpUrl = null;
			
			httpUrl = (HttpURLConnection) url.openConnection();
			
			httpUrl.setConnectTimeout(3000);
			
			int iStatus = httpUrl.getResponseCode();
			//如果取得的网页状态不对,就是出问题了
			if(iStatus == 200){
				
				return "0";
			}else{
				return "1";
				
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "1";
		}
		
		
	}
	
	public static boolean isHostConnectable(String host,int port){
		
		Socket socket = new Socket();
		
		try {
			socket.connect(new InetSocketAddress(host, port));
		} catch (IOException e) {

			return false;
			
		}finally{
			
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return true;
	}
}

Timer与TimerTask

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

import org.springframework.beans.factory.InitializingBean;

public class TestTimerTask implements InitializingBean{

	//在项目启动三分钟之后执行任务
	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		Timer timer = new Timer();
		TimerTask task = new TimerTask() {
			@SuppressWarnings("unchecked")
			public void run() {
				//执行定时任务的代码
				
			}
		};
		timer.schedule(task, 1000*60*3);
	}

}

Quartz

<dependency>
    	
    	<groupId>org.quartz-scheduler</groupId>
    	
    	<artifactId>quartz</artifactId>
    	
    	<version>2.3.0</version>
    	
	</dependency>

	<dependency>

		<groupId>org.quartz-scheduler</groupId>

		<artifactId>quartz-jobs</artifactId>

		<version>2.3.0</version>

	</dependency>
<bean id="myjob" class="com.xiaoi.quartz.MyJob"></bean>

	<!-- 注册jobDetail,通过反射调用自定义任务对象 -->
	<bean id="myJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<!-- 目标对象 -->
		<property name="targetObject">
			<ref bean="myjob"/>
		</property>

		<property name="targetMethod">
			<value>sendMessage</value>
		</property>
	</bean>


	<!-- CronTriggerFactoryBean:触发器 触发什么任务 什么时间触发 -->
	<bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<!-- 配置触发哪个任务 -->
		<property name="jobDetail">
			<ref bean="myJobDetail"/>
		</property>
		<!-- 什么时间触发任务 cronExpression:cron表达式 每隔5秒钟执行一次任务 -->
		<property name="cronExpression">
			<value>0 0/2 * * * ?</value>
		</property>
	</bean>
	
	<!-- SchedulerFactoryBean:配置计划调度器容器 -->
	<bean lazy-init="false" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="myTrigger"/>
			</list>
		</property>
	</bean>

public class MyJob {
	
	public void sendMessage(){
		
		System.out.println("方法执行了:"+new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date()));
		
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值