Exemplo n.º 1
0
        public void Execute(IJobExecutionContext context)
        {
            lock (locker)
            {
                if (_isRunning)
                {
                    return;
                }
                _isRunning = true;
            }

            try
            {
                if (!Directory.Exists(BackUpDir))
                {
                    Directory.CreateDirectory(BackUpDir);
                }

                //数据库名
                string dbName = EfDbContext.DbName;

                //要备份的数据库名
                string dbBackName = dbName + "_" + DateTime.Now.ToString("yyyyMMdd") + ".bak";
                //数据库全路径
                string dbFullPath = Path.Combine(BackUpDir, dbBackName);

                if (File.Exists(dbFullPath))
                {
                    //已经存在
                    NLogHelper.Warn($"数据库备份{dbFullPath}已经存在,本次备份放弃");
                    //已经存在
                    return;
                }

                string backupSql = string.Format(BackUpSql, dbName, dbFullPath);

                //不能在事务调用
                //路径中的目录必须存在,否则抛异常
                EfDbContext.ExecuteRawNonQuery(backupSql);
            }
            catch (Exception ex)
            {
                Log4netHelper.Error("备份数据库失败:" + ex);
            }
            finally
            {
                lock (locker)
                {
                    _isRunning = false;
                }
            }
        }