首页 > 技术文章 > vs widows服务的开发

fogwang 2015-06-24 15:45 原文

最近再做一个视频管理系统,发现用户提交时实时转换视频非常慢。于是有了通过建立一个单独的服务。通过服务定时查询数据库,是否有需要转换的视频来解决问题。现把过程记录下来,已供参考

1、新建widows 服务项目

  

2、增加查询定时器在服务启动时

  protected override void OnStart(string[] args)
        {
        // 单位为毫秒
         System.Timers.Timer timer = new System.Timers.Timer(1000);
         
          timer.AutoReset = true;  
 
         timer.Enabled = true;

         timer.Elapsed += timer_Elapsed;  
 
          timer.Start();  


        }

3、通过Timer的Elapsed事件处理定时任务

 

 void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {    // 加载外置配置文件
                  //得到当前服务的安装路径
               string basepath = AppDomain.CurrentDomain.BaseDirectory;
                XmlDocument xml = new XmlDocument();
          
                xml.Load(basepath + "\\videoconvertconfig.xml");
                XmlNode rootNode = xml.SelectSingleNode("root");
               
               
                string sqlConn = rootNode.Attributes["sqlConn"].Value;
                //得到ffmpeg的路径
                string ffmpegPath = rootNode.ChildNodes[0].Attributes["path"].Value;

            try
            {
                using (SqlConnection conn = new SqlConnection(sqlConn))
                {
                    conn.Open();
                    SqlDataAdapter data = new SqlDataAdapter("select videoaddress,id from viedoList where isconvert=0", conn);
                    DataSet ds = new DataSet();
                    data.Fill(ds);
                    DataTable VideoList = ds.Tables[0];
                    VideoConvert vc = new VideoConvert();
                    foreach (DataRow dr in VideoList.Rows)
                    {
                      // 视频转换
                        vc.convertVideo(basePath, ffmpegPath, dr[0].ToString()); 
                     //  转换成功 更新数据库
                        updateData(conn,dr[1].ToString());
                    }
                }

            }
            catch (Exception err) { Common.WriteFile(basePath+"/log/log.txt", err.Message); }
        }

  

推荐阅读