/***************************************************************************
                Scheduler 
                -----------------------------------------
	begin      : 2011/11/01
	copyright  : (C) 2011 SolutionBox Inc.
	author     : Service 1 Team
	email      : svc1@solbox.com
	version    : 3.0.1

    CopyRight(C) 2011 SolutionBox Inc. All Rights reserved.
    Redistribution and use in source and binary forms, with or with out
    modification, are not permitted in outside of SolutionBox Inc.
***************************************************************************/
#ifndef __SCHEDULER_H__
#define __SCHEDULER_H__

#include <sys/time.h>
#include <errno.h>
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
#include <list>
#include <algorithm>

using namespace std;

struct task_info
{
	short	tasktype;
	int64_t	spendtime;
	union 
	{
		int		interval;
		int		hour;
	}timeval;
	time_t	lastendtime;
	time_t	lastruntime;
	task_info() 
		: tasktype(-1), spendtime(0), lastendtime(0), lastruntime(0)	{}
} ;

typedef struct task_info task_info;

class CScheduler
{
public:
	enum TASK_TYPE
	{
		TIME_UNKNOWN	=	-1,
		TIME_ONCE		=	0,
		TIME_INTERVAL	=	1		
	};

public:
	CScheduler();
	~CScheduler();

	int run();

	bool addtask(short tasktype, int val);
	pthread_t gettimerhandle() {return m_htimerthread;}
	bool whetherdetach();
	bool updatelastendtime(int taskindex, time_t newtime);

	void printtasklist();

	void	setexit(bool v);
	bool	isexit() { return m_exit; }
	
private:
	static void* TimerFn(void* pdata);
	static void* WorkFn(void* pdata);

private:
	bool			m_exit;	
	map<int, task_info>	m_taskmap;

	pthread_t			m_htimerthread;
	pthread_cond_t		m_timercond;
	pthread_mutex_t		m_timermutex;

	pthread_t			m_hworkthread;
	pthread_cond_t		m_workcond;
	pthread_mutex_t		m_workmutex;

	pthread_mutex_t		m_updatemutex;
};


#endif // __SCHEDULER_H__
