我有一個ASP.NET方法,它從數據庫中提取用戶數據併爲我正在構建的Web應用程序的用戶創建登錄憑據。定期在幕後執行一段代碼
var userDataList = new List<UserInfo>();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
try
{
//open SQL connection
conn.Open();
SqlCommand getSumOfHours = new SqlCommand("SELECT LoginName, Email FROM [User] WHERE Deleted IS NULL", conn);
//execute command and retrieve primary key from the above insert and assign to variable
SqlDataReader reader = getSumOfHours.ExecuteReader();
while (reader.Read())
{
userDataList.Add(new UserInfo
{
userName = reader.GetString(0),
email = reader.GetString(1)
});
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.ToString());
}
finally
{
conn.Close();
}
foreach (var item in userDataList)
{
//System.Diagnostics.Debug.WriteLine(item.userName + " " + item.email);
if (!(Roles.RoleExists("user")))
{
Roles.CreateRole("user");
}
if (Membership.GetUser(item.userName) == null)
{
Membership.CreateUser(item.userName, "password", item.email);
Roles.AddUserToRole(item.userName, "user");
}
}
}
public class UserInfo
{
public string userName { get; set; }
public string email { get; set; }
}
它完美的工作,但目前我通過按下頁面上的按鈕執行它。這並不理想,因爲有人必須記住按下按鈕才能執行。當站點在服務器上時,是否有可能讓站點每隔幾個小時在幕後執行這段代碼?
將其設置爲控制檯應用程序並設置SQL作業或Windows任務。 –