监视线程

一个监视类,可以实现数据的分时更新功能
    环境:.NET,C#
    /// <summary>
    /// 监控线程类
    /// </summary>
    public class WatchDogOpt
    {
        protected struct ____Task____
        {
            public long taskId;
            public WatchFunc function;
            public int delaySecond;
            public int comeSecond;
            public int remainTimes;
            public ____Task____(WatchFunc function, int delaySecond, int effectTimes, int comeSecond)
            {
                this.taskId = DateTime.Now.Ticks;
                this.function = function;
                this.delaySecond = delaySecond;
                this.remainTimes = effectTimes;
                this.comeSecond = comeSecond;
            }
        };
        protected struct ____Thread____
        {
            public Thread thread;
            public long threadId;
            public ____Thread____(Thread thread, long threadId)
            {
                this.thread = thread;
                this.threadId = threadId;
            }
        }
        static protected int objectNumber = 0;
        private IList<____Task____> taskList;
        private IList<____Thread____> threadList;
        private int pastTime;
        private int state;
        /// <summary>
        /// 当前已创建的实例数,只读
        /// </summary>
        public int ObjectNumber
        {
            get { return objectNumber; }
        }
        /// <summary>
        /// 监视线程代理
        /// </summary>
        public delegate void WatchFunc(object isEnd);
        /// <summary>
        /// 构造函数
        /// </summary>
        public WatchDogOpt()
        {
            taskList = new List<____Task____>();
            threadList = new List<____Thread____>();
            pastTime = 0;
            state = -1;
            objectNumber++;
        }
        /// <summary>
        /// 查询任务是否完成
        /// </summary>
        public bool CheckTask(long taskId)
        {
            foreach (____Thread____ threadmsg in threadList)
            {
                if (threadmsg.threadId == taskId && threadmsg.thread.ThreadState != ThreadState.Stopped)
                    return false;
            }
            return true;
        }
        /// <summary>
        /// 清理任务
        /// </summary>
        public bool ClearTask(long taskId)
        {
            foreach (____Thread____ threadmsg in threadList)
            {
                if (threadmsg.threadId == taskId && threadmsg.thread.ThreadState != ThreadState.Stopped)
                    threadmsg.thread.Abort();
            }
            return true;
        }
        /// <summary>
        /// 添加需要处理的任务
        /// 返回值为任务编号,此编号将挂接到所有任务上
        /// </summary>
        public long TaskAdd(WatchFunc taskFunc, int delaySecond, int effectTimes)
        {
            taskList.Add(new ____Task____(taskFunc, delaySecond, effectTimes, pastTime));
            return taskList[taskList.Count - 1].taskId;
        }
        /// <summary>
        /// 删除需要处理的任务
        /// </summary>
        public bool TaskDel(long taskId)
        {
            foreach (____Task____ task in taskList)
            {
                if (task.taskId == taskId)
                    taskList.Remove(task);
            }
            return true;
        }
        /// <summary>
        /// 开始监视
        /// </summary>
        public void Start()
        {
            Thread thread = new Thread(new ThreadStart(Work));
            thread.Priority = System.Threading.ThreadPriority.BelowNormal;
            state = 1;
            thread.Start();
        }
        /// <summary>
        /// 结束监视
        /// </summary>
        public void Stop()
        {
            if (state != -1)
                state = 2;
        }
        /// <summary>
        /// 暂停监视
        /// </summary>
        public void Suspend()
        {
            if (state != -1)
                state = 0;
        }
        /// <summary>
        /// 恢复监视
        /// </summary>
        public void Continue()
        {
            if (state != -1)
                state = 1;
        }
        private void Work()
        {
            while (true)
            {
                Thread.Sleep(1000);
                if (state == 0)
                    continue;
                if (state != 1)
                    break;
                if ((++pastTime % 2) == 0)
                    ReFleshAllThread();
                for (int i = 0; i < taskList.Count; i++)
                {
                    if ((pastTime - taskList.comeSecond) % taskList.delaySecond == 0)
                    {
                        Thread thread = new Thread(new ParameterizedThreadStart(taskList.function));
                        thread.Priority = System.Threading.ThreadPriority.AboveNormal;
                        if (taskList.remainTimes == int.MinValue || taskList.remainTimes > 0)
                        {
                            thread.Start(false);
                            ____Task____ task = taskList;
                            task.remainTimes--;
                            taskList.RemoveAt(i);
                            taskList.Insert(i, task);
                        }
                        else
                        {
                            thread.Start(true);
                            taskList.RemoveAt(i--);
                        }
                        threadList.Add(new ____Thread____(thread, taskList.taskId));
                    }
                }
            }
        }
        private void ReFleshAllThread()
        {
            for (int i = 0; i < threadList.Count;)
            {
                if (threadList.thread.ThreadState == ThreadState.Stopped)
                    threadList.RemoveAt(i);
                else
                    i++;
            }
        }
    }

好的,以下是一个简单的使用 Python 实现监视线程的示例代码: ```python import threading import psutil # 使用 psutil 库监视系统资源 class MonitorThread(threading.Thread): def __init__(self, interval): threading.Thread.__init__(self) self.interval = interval self.running = True def stop(self): self.running = False def run(self): while self.running: # 监视系统 CPU 占用率和内存使用情况 cpu_percent = psutil.cpu_percent(interval=self.interval) mem_info = psutil.virtual_memory() mem_percent = mem_info.percent mem_total = mem_info.total / 1024 / 1024 # 转换为 MB mem_used = mem_info.used / 1024 / 1024 # 处理监视数据 print(f"CPU 占用率:{cpu_percent}%") print(f"内存使用率:{mem_percent}%") print(f"内存总量:{mem_total:.2f} MB") print(f"已使用内存:{mem_used:.2f} MB") # 使用示例:创建一个间隔 5 秒的监视线程,运行 10 秒后停止 monitor_thread = MonitorThread(interval=5) monitor_thread.start() time.sleep(10) monitor_thread.stop() ``` 在这个示例代码中,我们定义了一个 `MonitorThread` 类,继承自 `threading.Thread` 类。在类的构造函数中,我们指定了监视间隔 `interval`,并设置了一个 `running` 标识来控制线程的运行和停止。 在 `run` 方法中,我们使用 `psutil` 库来监视系统 CPU 占用率和内存使用情况,并将监视到的数据进行处理和输出。 最后,在主程序中,我们创建了一个 `MonitorThread` 实例,并启动它。使用 `time.sleep` 函数让程序在运行 10 秒后停止监视线程
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值