Spring 加定時器

定時器功能咱們通常不經常使用, 可是一旦用到,那也是很是重要的, 今天咱們就講一下如何簡單快速的使用定時器spring

第一種方法, 使用註解的方式完成定時器ide

 1.在spring-servlet.xml文件中加入task的命名空間:spa

xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-4.0.xsd"

 2.而後使用task配置掃描註解code

<!-- 定時任務 -->
    <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  
    <task:scheduler id="qbScheduler" />  

 3. 此時就能夠直接使用@Scheduled(cron = "時間格式串"),應用該註解就能夠實現定時的功能xml

@Scheduled(cron = "0/5 * * * * ?")  //每隔5秒執行一次定時任務
    public void consoleInfo(){
        System.out.println("定時任務");
    }

第二種方法, 不使用註解, 直接配置blog

  首先ip

xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation=" http://www.springframework.org/schema/task   
        http://www.springframework.org/schema/task/spring-task-3.0.xsd」


<description>
        定時任務
    </description>
    //定時註解驅動
    <task:annotation-driven />
    //進行定時任務的類,將其定義爲一個bean
    <bean id="spaceStatisticsService" class="com.pojo.system.manager.sigar.impl.SpaceStatisticsServiceImpl"></bean>
    //經過task標籤,定義定時功能
    <task:scheduled-tasks>
        <task:scheduled ref="spaceStatisticsService" method="statisticSpace" cron="59 59 23 * * ?" />
    </task:scheduled-tasks>

  而後 要實現的代碼以下所示servlet

@Service
public class SpaceStatisticsServiceImpl implements SpaceStatisticsService
{
    @Override
    public void statisticSpace()
    {
        System.out.println("實現定時功能");
    }
}

--  關於如何調整執行時間, 請在網上自行搜索io

相關文章
相關標籤/搜索