global文件中的application_start方法中做: 定时器

本文介绍了一个ASP.NET应用程序如何使用系统定时器(System.Timers.Timer)来执行每分钟一次的任务。通过在应用程序启动(Application_Start)时初始化并启用定时器,可以实现周期性的后台处理。这种方法适用于需要定期执行维护或更新操作的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<%@ Application Language="C#" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<%@ import Namespace="System.Collections" %>
<%@ Import Namespace="System.IO" %>
//引入类库
<script runat="server">
//add by chairuirui 2013-3-26
void Application_Start(object sender, EventArgs e)
{
//在应用程序启动时运行的代码
System.Timers.Timer myTimer = new System.Timers.Timer(60000); // 每个一分钟判断一下
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent); //执行需要操作的代码,OnTimedEvent是要执行的方法名称
myTimer.Interval = 60000;
myTimer.Enabled = true;
}
void Application_End(object sender, EventArgs e)
{
//在应用程序关闭时运行的代码
}
void Application_Error(object sender, EventArgs e)
{
//在出现未处理的错误时运行的代码
}
void Session_Start(object sender, EventArgs e)
{
//在新会话启动时运行的代码
}
void Session_End(object sender, EventArgs e)
{
//在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式
//设置为 StateServer 或 SQLServer,则不会引发该事件。
}
private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
//需要的操作写在这个方法中
}

转载于:https://www.cnblogs.com/jett010/p/5955641.html

import time import zcanpro import tkinter as tk from tkinter import filedialog, messagebox, scrolledtext import threading # 全局变量 stopTask = False id = [] name = [] comment = [] data = [] out_str = "VERSION \"\"\n\n\nNS_ : \n\tNS_DESC_\n\tCM_\n\tBA_DEF_\n\tBA_\n\tVAL_\n\tCAT_DEF_\n\tCAT_\n\tFILTER\n\tBA_DEF_DEF_\n\tEV_DATA_\n\tENVVAR_DATA_\n\tSGTYPE_\n\tSGTYPE_VAL_\n\tBA_DEF_SGTYPE_\n\tBA_SGTYPE_\n\tSIG_TYPE_REF_\n\tVAL_TABLE_\n\tSIG_GROUP_\n\tSIG_VALTYPE_\n\tSIGTYPE_VALTYPE_\n\tBO_TX_BU_\n\tBA_DEF_REL_\n\tBA_REL_\n\tBA_DEF_DEF_REL_\n\tBU_SG_REL_\n\tBU_EV_REL_\n\tBU_BO_REL_\n\tSG_MUL_VAL_\n\nBS_:\n\nBU_:\n\n\n" def z_notify(type, obj): zcanpro.write_log("Notify " + str(type) + " " + str(obj)) if type == "stop": zcanpro.write_log("脚本停止") global stopTask stopTask = True def select_input_file(): file_path = filedialog.askopenfilename( title="选择输入文件", filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")] ) if file_path: input_entry.delete(0, tk.END) input_entry.insert(0, file_path) return file_path return None def select_output_file(): file_path = filedialog.asksaveasfilename( title="保存输出文件", filetypes=[("DBC文件", "*.dbc"), ("所有文件", "*.*")], defaultextension=".dbc" ) if file_path: output_entry.delete(0, tk.END) output_entry.insert(0, file_path) return file_path return None def run_script(): input_file = input_entry.get() output_file = output_entry.get() if not input_file or not output_file: messagebox.showerror("错误", "请选择输入和输出文件路径") return # 在新线程中运行脚本 threading.Thread(target=process_files, args=(input_file, output_file)).start() def process_files(input_path, output_path): global id, name, comment, data, out_str # 重置全局变量 id = [] name = [] comment = [] data = [] out_str = "VERSION \"\"\n\n\nNS_ : \n\tNS_DESC_\n\tCM_\n\tBA_DEF_\n\tBA_\n\tVAL_\n\tCAT_DEF_\n\tCAT_\n\tFILTER\n\tBA_DEF_DEF_\n\tEV_DATA_\n\tENVVAR_DATA_\n\tSGTYPE_\n\tSGTYPE_VAL_\n\tBA_DEF_SGTYPE_\n\tBA_SGTYPE_\n\tSIG_TYPE_REF_\n\tVAL_TABLE_\n\tSIG_GROUP_\n\tSIG_VALTYPE_\n\tSIGTYPE_VALTYPE_\n\tBO_TX_BU_\n\tBA_DEF_REL_\n\tBA_REL_\n\tBA_DEF_DEF_REL_\n\tBU_SG_REL_\n\tBU_EV_REL_\n\tBU_BO_REL_\n\tSG_MUL_VAL_\n\nBS_:\n\nBU_:\n\n\n" zcanpro.write_log("读取数据……") try: input = open(input_path, "r", encoding="UTF-8") lines = input.readlines() n = l = 0 while(l < len(lines)): if lines[l].strip() == "": l += 1 continue line = lines[l].strip('\n').split('\t') line.append("") # 防止index溢出 if line[0] == "ID" and line[2] == "名称" and line[4] == "帧格式": if line[5] == "扩展帧": line[1] = '9' + line[1][1:] id.append(str(int(line[1], 16))) name.append(line[3]) comment.append(line[7]) n += 1 data.append([]) zcanpro.write_log(f"读取ID: 0x{hex(int(id[n-1],10) & 0x1FFFFFFF)[2:].upper()}……") else: i = 0 if line[3] == "Intel": line[3] = "1" else: line[3] = "0" if line[4] == "": line[4] = "1" if line[5] == "": line[5] = "0" data[n-1].append(line) l += 1 input.close() except Exception as e: zcanpro.write_log(f"{e}") messagebox.showerror("错误", f"读取文件时出错: {e}") return zcanpro.write_log("数据读取完成") zcanpro.write_log("编写格式……") try: for i in range(n): out_str += "BO_ " + id[i] + " " + name[i] + ": 8 Vector__XXX\n" for j in range(len(data[i])): out_str += " SG_ " + data[i][j][0] + " : " + data[i][j][1] + "|" + data[i][j][2] + "@" + data[i][j][3] + "+ (" + data[i][j][4] + "," + data[i][j][5] + ") [0|0] \"" + data[i][j][6] + "\" Vector__XXX\n" out_str += "\n" out_str += "\n\n" for i in range(n): out_str += "CM_ BO_ " + id[i] + " \"" + comment[i] + "\";\n" for j in range(len(data[i])): out_str += "CM_ SG_ "+ id[i] + " " + data[i][j][0] + " \"" + data[i][j][7] + "\";\n" out_str += "BA_DEF_ SG_ \"GenSigSendType\" ENUM \"Cyclic\",\"OnWrite\",\"OnWriteWithRepetition\",\"OnChange\",\"OnChangeWithRepetition\",\"IfActive\",\"IfActiveWithRepetition\",\"NoSigSendType\";\nBA_DEF_ SG_ \"GenSigInactiveValue\" INT 0 0;\nBA_DEF_ BO_ \"GenMsgCycleTime\" INT 0 0;\nBA_DEF_ BO_ \"GenMsgSendType\" ENUM \"Cyclic\",\"not_used\",\"not_used\",\"not_used\",\"not_used\",\"Cyclic\",\"not_used\",\"IfActive\",\"NoMsgSendType\";\nBA_DEF_ BU_ \"NmStationAddress\" HEX 0 0;\nBA_DEF_ \"DBName\" STRING ;\nBA_DEF_ \"BusType\" STRING ;\nBA_DEF_ BU_ \"NodeLayerModules\" STRING ;\nBA_DEF_ BU_ \"ECU\" STRING ;\nBA_DEF_ BU_ \"CANoeJitterMax\" INT 0 0;\nBA_DEF_ BU_ \"CANoeJitterMin\" INT 0 0;\nBA_DEF_ BU_ \"CANoeDrift\" INT 0 0;\nBA_DEF_ BU_ \"CANoeStartDelay\" INT 0 0;\nBA_DEF_DEF_ \"GenSigSendType\" \"Cyclic\";\nBA_DEF_DEF_ \"GenSigInactiveValue\" 0;\nBA_DEF_DEF_ \"GenMsgCycleTime\" 0;\nBA_DEF_DEF_ \"GenMsgSendType\" \"NoMsgSendType\";\nBA_DEF_DEF_ \"NmStationAddress\" 0;\nBA_DEF_DEF_ \"DBName\" \"\";\nBA_DEF_DEF_ \"BusType\" \"CAN\";\nBA_DEF_DEF_ \"NodeLayerModules\" \"\";\nBA_DEF_DEF_ \"ECU\" \"\";\nBA_DEF_DEF_ \"CANoeJitterMax\" 0;\nBA_DEF_DEF_ \"CANoeJitterMin\" 0;\nBA_DEF_DEF_ \"CANoeDrift\" 0;\nBA_DEF_DEF_ \"CANoeStartDelay\" 0;\nBA_ \"DBName\" \"TEMP\";\n" for i in range(n): for j in range(len(data[i])): value_table = "" a = len(data[i][j][8:]) for c in reversed(data[i][j][8:]): a -= 1 if c != "": value_table += str(a) + " \"" + c + "\" " if value_table != "": out_str += "VAL_ "+ id[i] + " " + data[i][j][0] + " " + value_table + ";\n" except Exception as e: zcanpro.write_log(f"{e}") messagebox.showerror("错误", f"处理数据时出错: {e}") return zcanpro.write_log("格式编写完成") zcanpro.write_log("导出文件……") try: output = open(output_path, "w", encoding="ANSI") output.write(out_str) output.close() messagebox.showinfo("成功", f"文件已成功导出至: {output_path}") except Exception as e: zcanpro.write_log(f"{e}") messagebox.showerror("错误", f"导出文件时出错: {e}") return zcanpro.write_log("文件导出完成") # 创建GUI界面 def create_gui(): global input_entry, output_entry root = tk.Tk() root.title("DBC文件转换工具") root.geometry("600x400") # 输入文件选择 input_frame = tk.Frame(root) input_frame.pack(pady=10, padx=20, fill=tk.X) tk.Label(input_frame, text="输入文件:").pack(side=tk.LEFT, padx=(0, 10)) input_entry = tk.Entry(input_frame, width=50) input_entry.pack(side=tk.LEFT, fill=tk.X, expand=True) input_btn = tk.Button(input_frame, text="浏览...", command=select_input_file) input_btn.pack(side=tk.RIGHT, padx=(10, 0)) # 输出文件选择 output_frame = tk.Frame(root) output_frame.pack(pady=10, padx=20, fill=tk.X) tk.Label(output_frame, text="输出文件:").pack(side=tk.LEFT, padx=(0, 10)) output_entry = tk.Entry(output_frame, width=50) output_entry.pack(side=tk.LEFT, fill=tk.X, expand=True) output_btn = tk.Button(output_frame, text="浏览...", command=select_output_file) output_btn.pack(side=tk.RIGHT, padx=(10, 0)) # 日志窗口 log_frame = tk.LabelFrame(root, text="日志输出") log_frame.pack(pady=10, padx=20, fill=tk.BOTH, expand=True) log_text = scrolledtext.ScrolledText(log_frame, height=10) log_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 重定向日志到GUI窗口 def write_log_gui(message): log_text.insert(tk.END, message + "\n") log_text.see(tk.END) # 替换zcanpro.write_log函数 original_write_log = zcanpro.write_log zcanpro.write_log = lambda msg: (original_write_log(msg), write_log_gui(msg)) # 运行按钮 run_btn = tk.Button(root, text="运行转换", command=run_script, height=2, width=20) run_btn.pack(pady=20) root.mainloop() # 主入口 if __name__ == "__main__": create_gui() 上述代码为何删除重定向到日志窗口的内容后运行两次就崩溃?
最新发布
08-15
在TSMaster中以下函数的各语句分别有什么作用// GEN BLOCK BEGIN Include #define TSMP_IMPL #include "TSMaster.h" #include "MPLibrary.h" #include "Database.h" #include "TSMasterBaseInclude.h" #include "Configuration.h" // GEN BLOCK END Include // CODE BLOCK BEGIN Timer FlashTimer MTAw // 定时器文档 "FlashTimer" TMPTimerMS FlashTimer; // CODE BLOCK END Timer FlashTimer // CODE BLOCK BEGIN Global_Definitions bool SinePos = true; // 初始状态设为正相位 // CODE BLOCK END Global_Definitions // CODE BLOCK BEGIN On_Var_Change On_Control_HeadLight Q29udHJvbC5IZWFkTGlnaHQsLTE_ // 变量变化事件 "On_Control_HeadLight" 针对变量 "Control.HeadLight" [On Written] void on_var_change_On_Control_HeadLight(void) { try { // 变量 = Control.HeadLight s32 s; app.get_system_var_int32("Control.HeadLight", &s); com.can_rbs_set_signal_value_by_address("0/EasyCAN/Gateway/LightState/HeadLight",s); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END On_Var_Change On_Control_HeadLight // CODE BLOCK BEGIN On_Var_Change On_Control_HazardLight Q29udHJvbC5IYXphcmRMaWdodCwtMQ__ // 变量变化事件 "On_Control_HazardLight" 针对变量 "Control.HazardLight" [On Written] void on_var_change_On_Control_HazardLight(void) { try { // 变量 = Control.HazardLight s32 s; app.get_system_var_int32("Control.HazardLight", &s); com.can_rbs_set_signal_value_by_address("0/EasyCAN/Gateway/LightState/FlashLight",s); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END On_Var_Change On_Control_HazardLight // CODE BLOCK BEGIN On_Timer NewOn_Timer1 Rmxhc2hUaW1lcg__ // 定时器触发事件 "NewOn_Timer1" for Timer FlashTimer void on_timer_NewOn_Timer1(void) { try { // 定时器 = FlashTimer double s1; com.can_rbs_get_signal_value_by_address("0/EasyCAN/Cluster/LightState/HeadLight",&s1); double s2; com.can_rbs_get_signal_value_by_address("0/EasyCAN/Cluster/LightState/FlashLight",&s2); s32 s; app.get_system_var_int32("Light.LightStatus", &s); int flash=0; if((int)s2==1) { if(s>=2) flash = 0; else flash = 1; } s = flash*2 + s1; log("light status is %d",s); app.set_system_var_int32("Light.LightStatus", s); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END On_Timer NewOn_Timer1 // CODE BLOCK BEGIN On_Start NewOn_Start1 // 启动事件 "NewOn_Start1" void on_start_NewOn_Start1(void) { try { // 程序启动事件 FlashTimer.start(); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END On_Start NewOn_Start1 // CODE BLOCK BEGIN On_Stop NewOn_Stop1 // 停止事件 "NewOn_Stop1" void on_stop_NewOn_Stop1(void) { try { // 程序停止事件 FlashTimer.stop(); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END On_Stop NewOn_Stop1 // CODE BLOCK BEGIN On_CAN_Rx TestControl MCwtMSwxODE4 // CAN报文接收事件 "TestControl" 针对标识符 = 0x71A void on_can_rx_TestControl(const TCAN* ACAN) { try { // 针对标识符 = 0x71A // if (ACAN->FIdxChn != CH1) return; // if you want to filter channel TTestControl_1 TestControl_1; TestControl_1.init(); // 在使用此结构体前调用这段初始化代码 TestControl_1.FCAN = *ACAN; // 若是在回调函数中,请用ACAN数据赋值FCAN s32 v = TestControl_1.DemoEnable; app.set_system_var_int32("Control.DemoEnable", v); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END On_CAN_Rx TestControl // CODE BLOCK BEGIN On_Var_Change On_Control_Ignition Q29udHJvbC5JZ25pdGlvbiwtMQ__ // 变量变化事件 "On_Control_Ignition" 针对变量 "Control.Ignition" [On Written] void on_var_change_On_Control_Ignition(void) { try { // 变量 = Control.Ignition s32 v; app.get_system_var_int32("Control.Ignition", &v); com.can_rbs_set_signal_value_by_address("0/EasyCAN/Gateway/Ignition_Info/StarterKey",v); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END On_Var_Change On_Control_Ignition // CODE BLOCK BEGIN On_Var_Change On_Control_EngSpeed Q29udHJvbC5FbmdTcGVlZCwtMQ__ // 变量变化事件 "On_Control_EngSpeed" 针对变量 "Control.EngSpeed" [On Written] void on_var_change_On_Control_EngSpeed(void) { try { // 变量 = Control.EngSpeed s32 v; app.get_system_var_int32("Control.EngSpeed", &v); if(v<0) v= -v; com.can_rbs_set_signal_value_by_address("0/EasyCAN/Engine/EngineData/EngSpeed",v); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END On_Var_Change On_Control_EngSpeed // CODE BLOCK BEGIN On_Shortcut 前照灯 ODE_ // 按键事件 "前照灯" 快捷键 = Q void on_shortcut_前照灯(const s32 AShortcut) { try { // 按键事件 = Q s32 v; app.get_system_var_int32("Control.HeadLight",&v); v = (v == 0) ? 1 : 0; app.set_system_var_int32("Control.HeadLight",v); com.can_rbs_set_signal_value_by_address("0/EasyCAN/Gateway/LightState/HeadLight",v); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END On_Shortcut 前照灯 // CODE BLOCK BEGIN On_Shortcut 危险灯 ODc_ // 按键事件 "危险灯" 快捷键 = W void on_shortcut_危险灯(const s32 AShortcut) { try { // 按键事件 = W s32 v; app.get_system_var_int32("Control.HazardLight",&v); v = (v == 0) ? 1 : 0; app.set_system_var_int32("Control.HazardLight",v); com.can_rbs_set_signal_value_by_address("0/EasyCAN/Gateway/LightState/HazardLight",v); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END On_Shortcut 危险灯 // CODE BLOCK BEGIN Step_Function NQ__ // 主step函数,执行周期 5 ms void step(void) { try { // 周期 = 5 ms s32 v1; app.get_system_var_int32("Control.carEnable", &v1); if(v1==0) return; app.set_system_var_int32("Control.Ignition", 1); s64 t64; double t; app.get_timestamp(&t64); t = t64 / 1000000.0 / 5; double v = sin(t)*3000; bool CurPos = v>0?true:false; if(!CurPos) v = -v; if(!CurPos == SinePos) { s32 hstatus; app.get_system_var_int32("Control.HeadLight", &hstatus); app.set_system_var_int32("Control.HeadLight", hstatus==0?1:0); if(SinePos) { s32 fstatus; app.get_system_var_int32("Control.HazardLight", &fstatus); app.set_system_var_int32("Control.HazardLight", fstatus==1?0:1); } } SinePos = CurPos; app.set_system_var_double("Control.EngSpeed", v); double baseTemp=70.0; double tempFactor=0.015*v; double engTemp = baseTemp + tempFactor; com.can_rbs_set_signal_value_by_address("0/EasyCAN/Engine/EngineData/EngTemp",engTemp); } catch (...) { log_nok("CRASH detected"); app.terminate_application(); }} // CODE BLOCK END Step_Function
07-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值