package cn.myapps.runtime.system.monitor.util;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadMXBean;
import java.text.DecimalFormat;
import java.util.Date;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;

import com.sun.management.OperatingSystemMXBean;

import cn.myapps.runtime.system.monitor.model.SystemMonitor;
import cn.myapps.scheduler.Job;

@PersistJobDataAfterExecution // 当job执行结束，持久化job信息到数据库
@DisallowConcurrentExecution // 保证job的唯一性（单例）
public class SystemMonitorWriteTxtJob extends Job{
	
	public static int executeTime=1000*30;

	ThreadMXBean threadMXBean=ManagementFactory.getPlatformMXBean(ThreadMXBean.class);
	
	OperatingSystemMXBean osBean=ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);

	MemoryMXBean memBean=ManagementFactory.getPlatformMXBean(MemoryMXBean.class);
	
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		try {
			String contextPath=System.getProperty("java.io.tmpdir");
			
			int mb=1024*1024;
			SystemMonitor monitor1=new SystemMonitor();
			//jvm使用cpu占用率
			double processCpuLoad=osBean.getProcessCpuLoad();
			processCpuLoad=processCpuLoad*100;
			if(processCpuLoad<0) processCpuLoad=0;
			//线程数
			int threadNum=threadMXBean.getThreadCount();
			//堆内存/非堆内存
			MemoryUsage heap=memBean.getHeapMemoryUsage();
			MemoryUsage nonHeap=memBean.getNonHeapMemoryUsage();
			long heapSizeUsed=heap.getUsed()/mb;
			long nonHeapSizeUsed=nonHeap.getUsed()/mb;
			
			//物理使用内存：
			//物理内存使用量
			DecimalFormat df=new DecimalFormat("0.00");
			long freePhysicalMemorySize=osBean.getFreePhysicalMemorySize();
			long totalPhysicalMemorySize=osBean.getTotalPhysicalMemorySize();
			String physicalMemorySizeUse=df.format((float)(totalPhysicalMemorySize-freePhysicalMemorySize)/mb);
			
			//时间：time
			Date date=new Date();
			
			monitor1.setCpuLoad(processCpuLoad);
			monitor1.setThreadNum(threadNum);
			monitor1.setHeapSizeUsed(heapSizeUsed);
			monitor1.setNonHeapSizeUsed(nonHeapSizeUsed);
			monitor1.setTime(date.getTime());
			monitor1.setTotalMemorySize(Double.valueOf(physicalMemorySizeUse));
			
			SystemMonitorUtil.writeFile(monitor1, contextPath + File.separator + "systemMonitor.txt");
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	

}
