「java接任务」java 并发执行任务

博主:adminadmin 2023-01-18 03:24:08 292

今天给各位分享java接任务的知识,其中也会对java 并发执行任务进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

JAVA制作一个任务列表

JAVA 的列表 方式 迅雷的 是执行任务后定时排队列表

以下思路 ,

1)java.util.Timer.

2)ServletContextListener.

3)org.springframework.scheduling.timer.ScheduledTimerTask

1)java.util.Timer

这个方法应该是最常用的,不过这个方法需要手工启动你的任务:

Timer timer=new Timer();

timer.schedule(new ListByDayTimerTask(),10000,86400000);

这里的ListByDayTimerTask类必须extends TimerTask里面的run()方法。

2)ServletContextListener

这个方法在web容器环境比较方便,这样,在web server启动后就可以

自动运行该任务,不需要手工操作。

将ListByDayListener implements ServletContextListener接口,在

contextInitialized方法中加入启动Timer的代码,在contextDestroyed

方法中加入cancel该Timer的代码;然后在web.xml中,加入listener:

listener

listener-classcom.sysnet.demo.util.MyTimerTask/listener-class

/listener

3)org.springframework.scheduling.timer.ScheduledTimerTask

如果你用spring,那么你不需要写Timer类了,在schedulingContext-timer

.xml中加入下面的内容就可以了:

?xml version="1.0" encoding="UTF-8"?

!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" ""

beans

bean id="timer" class="org.springframework.scheduling.timer.TimerFactoryBean"

property name="scheduledTimerTasks"

list

ref local="MyTimeTask1"/

/list

/property

/bean

bean id="MyTimeTask" class="com.qq.timer.ListByDayTimerTask"/

bean id="MyTimeTask1" class="org.springframework.scheduling.timer.ScheduledTimerTask"

property name="timerTask"

ref bean="MyTimeTask"/

/property

property name="delay"

value10000/value

/property

property name="period"

value86400000/value

/property

/bean

/beans

下面给出方法2的一个例子供大家参考:

Java代码:

import java.util.Timer;

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

public class MyTimerTask implements ServletContextListener{

private Timer timer = null;

@Override

public void contextDestroyed(ServletContextEvent event) {

// TODO Auto-generated method stub

timer.cancel();

event.getServletContext().log("定时器销毁");

System.out.println("停止备份程序……");

}

@Override

public void contextInitialized(ServletContextEvent event) {

//在这里初始化监听器,在tomcat启动的时候监听器启动,考试,大提示可以在这里实现定时器功能

timer = new Timer(true);

event.getServletContext().log("定时器已启动");//添加日志,可在tomcat日志中查看到

timer.schedule(new exportHistoryBean(event.getServletContext()),0,5*1000);//调用exportHistoryBean,0表示任务无延迟,5*1000表示每隔5秒执行任务,60*60*1000表示一个小时;

}

}

import java.util.Calendar;

import java.util.TimerTask;

import javax.servlet.ServletContext;

public class exportHistoryBean extends TimerTask

{

private static final int C_SCHEDULE_HOUR = 0;

private static boolean isRunning = false;

private ServletContext context = null;

public exportHistoryBean(ServletContext context)

{

this.context = context;

}

@Override

public void run()

{

Calendar c = Calendar.getInstance();

if(!isRunning)

{

if(C_SCHEDULE_HOUR == c.get(Calendar.HOUR_OF_DAY))

{

isRunning = true;

context.log("开始执行指定任务");

isRunning = false;

context.log("指定任务执行结束");

}

else

{

context.log("上一次任务执行还未结束");

}

}

}

}

web.xml里加入一下代码:

listener

listener-classcom.sysnet.demo.util.MyTimerTask/listener-class

/listener

java 并发执行任务 怎么做

/**

* 定时器

* */

public class TimeThread extends Thread {

public void run() {

Timer time = new Timer();

TimerTask tst = new TimerTask();//定时执行Rptlog类中的run方法

time.schedule(tst, 1000,10000);//1秒后执行,每10秒执行一次

}

}

接下来是实际执行的类

public class TimerSendTask extends java.util.TimerTask{

public void run() {

TimerTask tt = new TimerTask();

for(int i=0;iservice.getList().size();i++){//循环查询任务

定时清理任务 实现代码段...

....

}

}

}

再写多个任务的类

在这个地方执行以下就好了

TimerTask tst = new TimerTask();//定时执行Rptlog类中的run方法

time.schedule(tst, 1000,10000);//1秒后执行,每10秒执行一次

java 定时任务的几种实现方式

JDK 自带的定时器实现

// schedule(TimerTask task, long delay) 延迟 delay 毫秒 执行

// schedule(TimerTask task, Date time) 特定时间执行

public static void main(String[] args) {

for (int i = 0; i 10; ++i) {

new Timer("timer - " + i).schedule(new TimerTask() {

@Override

public void run() {

println(Thread.currentThread().getName() + " run ");

}

}, 1000);

}

}

2. Quartz 定时器实现

//首先我们需要定义一个任务类,比如为MyJob02 ,

//该类需要继承Job类,然后添加execute(JobExecutionContext context)方法,在

//这个方法中就是我们具体的任务执行的地方。

//由希望由调度程序执行的组件实现的接口

public class MyJob02 implements Job {

@Override

public void execute(JobExecutionContext context) throws JobExecutionException {

// TODO Auto-generated method stub

// 执行响应的任务.

System.out.println("HelloJob.execute,"+new Date());

}

}

public class QuartzTest5 {

public static void main(String[] args) throws Exception {

//SchedulerFactory 是一个接口,用于Scheduler的创建和管理

SchedulerFactory factory = new StdSchedulerFactory();

//从工厂里面拿到一个scheduler实例

//计划表(可能翻译的不太贴切),现在我们有了要做的内容,

//与调度程序交互的主要API

/*

* Scheduler的生命期,从SchedulerFactory创建它时开始,

到Scheduler调用shutdown()方法时结束;Scheduler被创建后,

可以增加、删除和列举Job和Trigger,以及执行其它与调度相关的操作

(如暂停Trigger)。但是,Scheduler只有在调用start()方法后,

才会真正地触发trigger(即执行job)

*/

Scheduler scheduler = factory.getScheduler();

//具体任务.

//用于定义作业的实例

//JobBuilder - 用于定义/构建JobDetail实例,用于定义作业的实例。

JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("job1", "group1").build();

//Trigger(即触发器) - 定义执行给定作业的计划的组件

//TriggerBuilder - 用于定义/构建触发器实例

CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")

.withSchedule(CronScheduleBuilder.cronSchedule("0/1  * * * * ?")).build();

scheduler.scheduleJob(job, trigger);

scheduler.start();

}

3. Spring  boot 任务调度(这个非常容易实现)

/*

*  开启对定时任务的支持

*  在相应的方法上添加@Scheduled声明需要执行的定时任务。

*/

@EnableScheduling

//@EnableScheduling注解来开启对计划任务的支持

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

@Component

public class ScheduledTasks {

private Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);

private    int     i=0;

//0 0 0 2 * ?

@Scheduled(cron="*  *  *  2  *  ?")

//@Scheduled 注解用于标注这个方法是一个定时任务的方法

public void testFixDelay() {

logger.info("执行方法"+i++);

}

Java程序员的工作职责是什么呢?

java程序员每天要做的主要有:需求分析、框架选型、编码、测试、改bug等。

1、需求分析

在接到开发任务时,java程序员首先要对这个任务进行需求分析,了解时间节点、任务目标、需要什么元素等等,梳理好工作流程之后再开始进行开发工作。

2、框架选择

在开始编程之前还需要先调研有哪些工具或者框架可以来做这个事,分别有哪些优缺点,针对自己的项目,哪个比较合适一些,甚至可以写个demo来试看看是否有什么问题。

3、编码

准备工作都做好后就要开始编程开发了,java程序员每天大部分时间都被用来编程。

4、测试并改bug

程序编写好后需要程序员做初步的测试看看程序能不能跑起来同时生产程序在跑的过程中,可能会出现各种各样的异常,如果有问题需要程序员及时查看日志,查问题,解决问题。

java中ExecutorService的线程池如何暂停任务和继续任务? 有这样的函数吗?

接口 java.util.concurrent.ExecutorService 表述了异步执行的机制,并且可以让任务在后台执行。一个 ExecutorService 实例因此特别像一个线程池。事实上,在 java.util.concurrent 包中的 ExecutorService 的实现就是一个线程池的实现。

这里有一个简单的使用Java 实现的 ExectorService 样例:

使用 newFixedThreadPool() 工厂方法创建一个 ExecutorService ,上述代码创建了一个可以容纳10个线程任务的线程池。其次,向 execute() 方法中传递一个异步的 Runnable 接口的实现,这样做会让 ExecutorService 中的某个线程执行这个 Runnable 线程。

在JAVA中如何实现长时间任务

一、问题背景 在应用程序中我们经常需要一个类去完成像数据处理、监听事件或检查另一个类的活动等任务。为了达到这个目标,我们可能使用带有一套锁和消息通知的线程。JAVA 线程API已经很好的文档化,但为了使线程能够正确而高效地运行,程序员仍然需要丰富的编程经验并编写大量的代码。通过应用本篇文章中讨论的框架,程序员能够避免忍受煎熬写大量的代码,快速创建健壮的应用程序。 二、长时间运行任务的程序框架 Framework for long-running tasksThe primary thing about a long-lived task is that it should somehow be kept running during the application lifetime. The right way to accomplish this is to provide a thread of execution for a particular task. You create a task as a thread or as an implementation of the java.lang.Runnable interface. If you implement Runnable, you can gain better object-oriented design and avoid the single-inheritance problems. You can also more efficiently manipulate with Runnable instances, for example, using a thread pool that usually needs a Runnable instance, not a thread, to run. 关于长时间运行的任务的主要事情是如何在应用程序的生命期使它一直保持运行。实现的恰当方法是提供一个线程来执行这个特定的任务。我们可以通过继承Thread类或实现java.lang.Runnable接口来达到该目标。如果采用实现Runnable接口的方式,就可以能够获得更好的面向对象的设计,同时可以避免JAVA中的单继承问题。另外,我们也能更有效的处理Runnable实例(例如使用线程池通常需要一个Runnable实例而不是线程来运行)。 The essence of the framework is the abstract class Worker ( Listing A), which implements the Runnable interface and provides the helper methods for efficient task handling. Some of the methods are fully implemented, like the run() method, but some are abstract and have to be filled by you. If you want to create a long-running class, you need only to extend the Worker class and implement several abstract methods. Let’s look at these methods in more detail. 框架的基础是一个叫Worker的抽象类,它实现了Runnable接口,并提供了有效处理任务的好方法。这些方法有些已经被实现,如run()方法,但有些是抽象方法,开发人员必须自己来实现。如果要创建一个长时间运行的类,你只需要继承Worker类并实现几个抽象方法。让我们看看这些方法的细节。 The run() method of the Worker class is designed to continuously execute the work() method until it is stopped. The work() method can be responsible for data processing, reaction to some event, file reading or writing, SQL execution, etc. It can throw an exception, so it is a good practice to propagate it and let the run() method handle it. Worker 类的run()方法被设计成只要不停止运行就持续的执行work()方法。work()方法可以负责数据处理、事件响应、文件读写、,执行SQL命令等操作。这样work()方法能够抛出异常,并将异常传给run(),然后由run()方法来处理这些异常。 The run() method has two levels of try-catch clause: outside and inside the while-loop. The first try-catch clause is meant to catch all nonprogrammed exceptions and guarantee that the run() method never exits. The second clause will catch any kind of exceptions belonging to business logic and behave accordingly. If some waiting operation takes place in the work() method (e.g., waiting on an InputStream or a Socket), it is advisable to propagate an InterruptedException. The thing to keep in mind is that the work() method does not need to have any while-loop to keep it going as long as an application runs. The Worker does this for you. run()方法有内外两层try-catch语句:一层处于while-loop循环外,一层在while-loop循环内。前一个try-catch用于捕获非编程异常以确保run()方法不退出。后一个try-catch语句捕获关于业务逻辑和相应行为的各种异常。如果在work()方法中发生了一些等待操作(例如等待一个输入流或一个Socket),抛出一个InterruptedException的方法是可取的。要记住的是只要应用程序在运行,work()方法不需要任何while-loop循环去维持它运行,这一切由Worker代办了。 When the run() method starts, it calls the prepareWorker() which is designed to prepare all resources needed for a long-running task (Listing A). In this method call, you can, for example, establish a database connection or open a file that will be used further. It is especially good to place here some blocking operations like opening a socket, because they will be done in a separate thread and thus will not block the main thread of execution. run()开始时,调用prepareWorker()方法来准备长时间运行任务需要的所有资源(参考程序清单A)。例如 ,在这个方法中可以打开一个将要用到的数据库连接或文件。尤其对于那些像建立一个socket这样的阻塞操作放在这儿是很好的。因为若让它们在一个独立的线程中运行,则不会阻塞主线程的执行。 The opposite of the previous method is the releaseWorker() which is called when the run() method is about to exit (Listing A). Here, you can put the code to dispose of system resources used by this task or to perform other cleanup. This method is similar to java.lang.Object.finalize(), but it is explicitly called before a thread terminates. 与前面方法相反的是releaseWorker(),它在run()方法准备退出时被调用(参考程序清单A)。在该方法中你可以编写那些释放系统资源或执行其它清除动作的代码。该方法类似于java.lang.Object.finalize(),但它在线程中止时被显式的调用。 三、框架中的错误处理机制 Handling errors in the frameworkAnother important method is the handleError(), which takes a java.lang.Throwable as a parameter. This method is called each time an error situation occurs within the run() method. It is up to you how to implement error handling. One way is to log errors and control task termination by calling halt() method (Listing A). The isCondition() method is used to tell whether execution of the work() method can be started, thus allowing granular control over a task. It is useful in event-triggered frameworks when execution of the work() method is pending until some condition?for example, a buffer is not empty?is fulfilled. In Worker’s implementation, the condition is checked upon a lock notification and periodically with a time interval you specify in the setTimeout() method (Listing A). If you don’t need any waiting blocks in a task, just make the isCondition() method always return true. isCondition()方法用于判断work()方法是否能够被执行。因此允许细粒度地控制任务。这在事件触发的框架中非常有用。当work()方法的执行条件未满足时,work方法将被挂起,直到条件完全满足(例如,缓存区非空)。在Worker的实现中这个条件将按在方法setTimeout()中指定的时间周期地检查一个锁通知。如果在任务中不需要任何等待阻塞,仅仅只要使isCondition()方法总是返回真值。四、任务终止时机

java接任务的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java 并发执行任务、java接任务的信息别忘了在本站进行查找喔。