package com.fos.demo.task.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.fos.demo.mybatis.entity.DemoUserEntity;
import com.fos.demo.mybatis.service.DemoUserService;

/**
 * Spring 自带任务定时器
 * @author Administrator
 *
 */
@Component
public class DemoTask {

    @Value("#{C['name']}")
    private String name;
    
    @Autowired
    DemoUserService demoUserService;
    
    private static boolean isRunning = false;
//    @Scheduled(cron="0 * * * * *")     //第二种方式
    public void singing(){
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println("当前时间："+sdf.format(date));
        System.out.println("项目名称："+name);
    }

    /**
     * 心跳更新。启动时执行一次，之后每隔2秒执行一次
     */
//    @Scheduled(fixedRate = 1000*2)
    public void print(){
        System.out.println("===================================");
        if(isRunning){
            System.out.println("上次程序还在运行中！");
            return;
        }
        try {
            isRunning = true;
            System.out.println("心跳更新。启动时执行一次，之后每隔2秒执行一次 ");
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            
            DemoUserEntity user = demoUserService.getUser();
            System.out.println("当前时间："+user.getUserName());
            System.out.println("当前时间："+sdf.format(date));
            System.out.println("项目名称："+name);
            Thread.sleep(5*1000);
            isRunning = false;
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
