java项目设置定时执行任务的几种方式

最近在做项目的中过程中有一个需求:将一个公告在一个特定时间发送。于是上网查询定时执行任务,上面有三种定时执行任务的方式。分别是1.普通thread实现

2.TimerTask实现    3.ScheduledExecutorService实现。下面一一介绍,

public class Task1 {
public static void main(String[] args) {
  // run in a second
  final long timeInterval = 1000;
  Runnable runnable = new Runnable() {
  public void run() {
    while (true) {
      // ------- code for task to run
      System.out.println("Hello !!");
      // ------- ends here
      try {
       Thread.sleep(timeInterval);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      }
    }
  };
  Thread thread = new Thread(runnable);
  thread.start();
  }
}

二、用Timer和TimerTask

上面的实现是非常快速简便的,但它也缺少一些功能。
用Timer和TimerTask的话与上述方法相比有如下好处:

1.当启动和去取消任务时可以控制
2.第一次执行任务时可以指定你想要的delay时间

在实现时,Timer类可以调度任务,TimerTask则是通过在run()方法里实现具体任务。
Timer实例可以调度多任务,它是线程安全的。
当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务。

package com.gzydt.report.message.rest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Timer:可以调度任务
 * TimeTask:在run()方法中实现具体的任务
 * @author duanhongyan
 *
 */
public class TestTask {

	  public static void main(String[] args) {
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        // task to run goes here
        System.out.println("Hello !!!");
      }
    };
    Timer timer = new Timer();
    long delay = 0;
    long intevalPeriod = 1 * 1000;
    // schedules the task to be run in an interval
    timer.scheduleAtFixedRate(task, delay,
                                intevalPeriod);
  } 
	
}


三、ScheduledExecutorService

ScheduledExecutorService是从Java SE 5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。
相比于上两个方法,它有以下好处:

1.相比于Timer的单线程,它是通过线程池的方式来执行任务的
2.可以很灵活的去设定第一次执行任务delay时间
3.提供了良好的约定,以便设定执行的时间间隔

下面是实现代码,我们通过ScheduledExecutorService#scheduleAtFixedRate展示这个例子,通过代码里参数的控制,首次执行加了delay时间。

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Task3 {
  public static void main(String[] args) {
    Runnable runnable = new Runnable() {
      public void run() {
        // task to run goes here
        System.out.println("Hello !!");
      }
    };
    ScheduledExecutorService service = Executors
                    .newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
  }
}


针对这种任务只是发送一一次的任务我是采用了第二种较为简单的方式,直接用Timer去执行一个定时任务,执行完成一次之后自己断开,这里采用的是单例的模式,不会每次请求Timer的时候都去新增一个Timer()对象,是采用spirng注入的方式:

然后在NoticeRestImpl中调用timer服务


然后这样就可以使得Timer只是新建一个对象,然后通过这一个Timer(任务调度)来管理多个TimerTask(任务),单例模式的好处就在于此,对于那种每请求一次都要新建一个TIimer对象,然后如果有多个TimeTask任务就要用多个Timer来管理,不太合理

然后调用这个方法就是通过实现Timer的run()方法来多次执行指定的任务


还有一种情况:每隔一段时间对一个文件夹进行扫描,

配置如下

这是在我的服务里面配置的,具体的服务如下

package com.gzydt.license.manage.rest.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONObject;

import com.gzydt.license.manage.persist.entity.CenterIndexData;
import com.gzydt.license.manage.persist.entity.LicenseStatus;
import com.gzydt.license.manage.rest.util.ConfigUtil;
import com.gzydt.license.manage.rest.util.PDFXmlUtil;
import com.gzydt.license.manage.service.CenterDataService;

public class ThreadGetpdf extends Thread {
	private CenterDataService centerDataService;

	public void setCenterDataService(CenterDataService centerDataService) {
		this.centerDataService = centerDataService;
	}

	private Long delay;

	public void setDelay(Long delay) {
		this.delay = delay;
	}

	private String path = new ConfigUtil().getPdfPath();

	public void run() {
		// logger.debug("扫描文件夹线程启动!");
		// 临时:while(true)不可控,要修改,还没想好怎么改
		boolean tag = true;
		while (true) {
			// logger.debug("开始运行。");
			try {

				File file = new File(path);
				File[] files = file.listFiles();
				if (files.length == 0) {
					tag = false;
				}
				if (files != null) {
					for (File f : files) {
						// 将xml都转换为一个javabean对象
						String pdfPath = f.getPath();
						new PDFXmlUtil();
						// 解析pdf文件
						JSONObject param = new JSONObject();
						try {
							String pdf = PDFXmlUtil.getPDFXml(pdfPath);
							param = new JSONObject(pdf)
									.optJSONObject("businessData");
						} catch (Exception e) {
							// e.printStackTrace();

						}

						CenterIndexData entity = new CenterIndexData();
						entity.setHolder(param.optString("holder"));
						entity.setSerNum(param.optString("serNum"));
						entity.setLicAttrs(param.optString("licAttrs"));
						entity.setLicenseStatus((LicenseStatus.valueOf(param
								.optString("licenseStatus"))));
						entity.setLicName(param.optString("licName"));
						entity.setLicType(param.optString("licType"));
						entity.setStamper(param.optString("stamper"));
						String staDate = param.optString("staDate");
						DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
						Date date = null;
						try {
							 date = fmt.parse(staDate);
						} catch (Exception e) {
							e.printStackTrace();
						}
						
						entity.setStaDate(date);
						entity.setIssuer(param.optString("issuer"));
						entity.setProvideOrg(param.optString("provideOrg"));
						String pdfPathcopy = new ConfigUtil().getPdfPathcopy()
								+ f.getName();
						System.out.println(pdfPathcopy);
						entity.setPdfPath(pdfPathcopy);
						String toFilePath = new ConfigUtil().getPdfPathcopy();
						getFile2(f, toFilePath);
						centerDataService.add(entity);
					}
				}
			} catch (Exception e1) {
				// e1.printStackTrace();
				continue;
			}

			try {
				synchronized (this) {
					wait(delay);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
				continue;
			}
		}
	}
	

	public static void main(String[] args) {
		String pdfPath="D:/lic_repo/pdf/00177~00067~license~车艾丝凡带手机过来撒娇~4400001001030002~车艾丝凡带手机过来撒娇.pdf";
		String pdf = PDFXmlUtil.getPDFXml(pdfPath);
		System.out.println(pdf);
	}
	/**
	 * 将某文件夹下面的文件移动到另一个文件夹
	 * 
	 * @param dir
	 *            要移动的文件夹名
	 * @param toFilePath
	 *            移动后文件存储的新文件夹名
	 */
	private static void getFile(File dir, String toFilePath) {
		File[] files = dir.listFiles();
		try {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					getFile(files[i], toFilePath);
				} else {
					FileInputStream fis = new FileInputStream(
							files[i].getPath());
					FileOutputStream fos = new FileOutputStream(toFilePath
							+ "\\" + files[i].getName());
					byte[] bt = new byte[2048];
					int c;
					while ((c = fis.read(bt)) != -1) {
						try {
							fos.write(bt, 0, c);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					try {
						fos.flush();
						fos.close();
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					files[i].delete();
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 将某文件移动到另一个文件夹
	 * 
	 * @param dir
	 *            要移动的文件夹名
	 * @param toFilePath
	 *            移动后文件存储的新文件夹名
	 */
	private static void getFile2(File dir, String toFilePath) {

		try {

			FileInputStream fis = new FileInputStream(dir.getPath());
			FileOutputStream fos = new FileOutputStream(toFilePath + "\\"
					+ dir.getName());
			byte[] bt = new byte[2048];
			int c;
			while ((c = fis.read(bt)) != -1) {
				try {
					fos.write(bt, 0, c);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			try {
				fos.flush();
				fos.close();
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			dir.delete();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值