Skip to content

Commit

Permalink
Add Combined Scheduled Task
Browse files Browse the repository at this point in the history
  • Loading branch information
patrix87 committed Dec 11, 2022
1 parent e72e1de commit be1df90
Show file tree
Hide file tree
Showing 31 changed files with 379 additions and 24 deletions.
11 changes: 11 additions & 0 deletions functions/process/Get-Lock.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
function Get-Lock {
[CmdletBinding()]
[OutputType([boolean])]
param (
)
if ((Test-Path -Path ".\servers\$($Server.UID).LOCK" -PathType "Leaf" -ErrorAction SilentlyContinue)) {
return $true
}
return $false
}
Export-ModuleMember -Function Get-Lock
15 changes: 15 additions & 0 deletions functions/process/Lock-Process.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function Lock-Process {
[CmdletBinding()]
[OutputType([boolean])]
param (
)
try {
$null = New-Item -Path ".\servers\" -Name "$($Server.UID).LOCK" -ItemType "file" -Force -ErrorAction SilentlyContinue
Write-ScriptMsg "Process Locked."
}
catch {
return $false
}
return $true
}
Export-ModuleMember -Function Lock-Process
16 changes: 16 additions & 0 deletions functions/process/Unlock-Process.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function Unlock-Process {
[CmdletBinding()]
[OutputType([boolean])]
param (
)
try {
#Delete the LOCK file based on the Server UID.
$null = Remove-Item -Path ".\servers\$($Server.UID).LOCK" -Confirm:$false -ErrorAction SilentlyContinue
Write-ScriptMsg "Process Unlocked."
}
catch {
return $false
}
return $true
}
Export-ModuleMember -Function Unlock-Process
1 change: 1 addition & 0 deletions functions/server/Start-Server.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ function Start-Server {
} else {
$null = Set-Priority -ServerProcess $ServerProcess
}
$null = Register-TaskConfig
}
catch {
Write-Error $_
Expand Down
1 change: 1 addition & 0 deletions functions/util/Exit-WithError.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ function Exit-WithError
)
#Write error in red on black, stop logging, pause, exit.
Write-Host -ForegroundColor "Red" -BackgroundColor "Black" -Object $ErrorMsg
Unlock-Process
Stop-Transcript
if ($Global.PauseOnErrors){
Read-Host "Press Enter to close this window."
Expand Down
12 changes: 12 additions & 0 deletions functions/util/Get-TaskConfig.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
function Get-TaskConfig {
Write-ScriptMsg "Getting Tasks Schedule..."
$NextAlive = Get-IniValue -file ".\servers\$($Server.UID).INI" -key "NextAlive"
$NextUpdate = Get-IniValue -file ".\servers\$($Server.UID).INI" -key "NextUpdate"
$NextRestart = Get-IniValue -file ".\servers\$($Server.UID).INI" -key "NextRestart"
return {
NextAlive: $NextAlive,
NextUpdate: $NextUpdate,
NextRestart: $NextRestart
}
}
Export-ModuleMember -Function Get-TaskConfig
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
function Register-UpdateTask {
$action = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass -File $scriptpath -ServerCfg `"$ServerCfg`" -UpdateCheck" -WorkingDirectory $dir
$trigger = New-ScheduledTaskTrigger -Daily -At 12am -RandomDelay (New-TimeSpan -Minutes $Global.UpdateCheckFrequency)
function Register-Task {
$action = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass -File $scriptpath -ServerCfg `"$ServerCfg`" -Task" -WorkingDirectory $dir
$trigger = New-ScheduledTaskTrigger -Daily -At 12am -RandomDelay (New-TimeSpan -Minutes $Global.TaskCheckFrequency)
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
$description = "Check if updates are available for $($server.Name)"
$title = "UpdateCheck-$($server.Name)"
$description = "Run Tasks for $($server.UID)"
$title = "Tasks-$($server.UID)"
$task = New-ScheduledTask -Description $description -Action $action -Trigger $trigger -Settings $settings
$RegisteredTask = Register-ScheduledTask $title -InputObject $task
$RegisteredTask.Triggers.Repetition.Duration = "P1D" #Repeat for a duration of one day
$RegisteredTask.Triggers.Repetition.Interval = "PT$($Global.UpdateCheckFrequency)M" #Repeat every 30 minutes, use PT1H for every hour
$RegisteredTask.Triggers.Repetition.Interval = "PT$($Global.TaskCheckFrequency)M" #Repeat every X minutes, use PT1H for every hour
$null = Set-ScheduledTask $RegisteredTask
}
Export-ModuleMember -Function Register-UpdateTask
Export-ModuleMember -Function Register-Task
13 changes: 13 additions & 0 deletions functions/util/Register-TaskConfig.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function Register-TaskConfig {
Write-ScriptMsg "Registering Tasks Schedule..."
try {
$null = New-Item -Path ".\servers\" -Name "$($Server.UID).INI" -ItemType "file" -Force -ErrorAction SilentlyContinue
Write-ScriptMsg "Tasks Schedule Registered."
}
catch {
return $null
}
Update-TaskConfig -Alive -Update -Restart
return $true
}
Export-ModuleMember -Function Register-TaskConfig
16 changes: 16 additions & 0 deletions functions/util/Remove-TaskConfig.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function Remove-TaskConfig {
[CmdletBinding()]
[OutputType([boolean])]
param (
)
try {
#Delete the INI file based on the Server UID.
$null = Remove-Item -Path ".\servers\$($Server.UID).INI" -Confirm:$false -ErrorAction SilentlyContinue
Write-ScriptMsg "Task Config Removed."
}
catch {
return $false
}
return $true
}
Export-ModuleMember -Function Remove-TaskConfig
6 changes: 6 additions & 0 deletions functions/util/Unregister-Task.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
function Unregister-UpdateTask {
$title = "Tasks-$($server.UID)"
$null = Unregister-ScheduledTask -TaskName $title -Confirm:$false -ErrorAction SilentlyContinue
Remove-TaskConfig
}
Export-ModuleMember -Function Unregister-UpdateTask
30 changes: 30 additions & 0 deletions functions/util/Update-TaskConfig.psm1
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

function Update-TaskConfig {
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[switch]$Alive,
[Parameter(Mandatory=$false)]
[switch]$Update,
[Parameter(Mandatory=$false)]
[string]$Restart
)

Write-ScriptMsg "Updating Tasks Schedule..."

if($Alive){
$NextAlive = (Get-Date).AddMinutes($Global.AliveCheckFrequency)
Set-IniValue -file ".\servers\$($Server.UID).INI" -key "NextAlive" -value $NextAlive
}

if($Update){
$NextUpdate = (Get-Date).AddMinutes($Global.UpdateCheckFrequency)
Set-IniValue -file ".\servers\$($Server.UID).INI" -key "NextUpdate" -value $NextUpdate
}

if($Restart){
$NextRestart = (Get-Date -Hour $Server.AutoRestartTime[0] -Minute $Server.AutoRestartTime[1] -Second $Server.AutoRestartTime[2]).AddDays(1)
Set-IniValue -file ".\servers\$($Server.UID).INI" -key "NextRestart" -value $NextRestart
}
}
Export-ModuleMember -Function Update-TaskConfig
6 changes: 6 additions & 0 deletions global.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ $GlobalDetails = @{

#Check for Update Frequency in Minutes
UpdateCheckFrequency = 15

#Check if the server is alive Frequency in Minutes
AliveCheckFrequency = 5

#Should be lower or equal to the two above
TaskCheckFrequency = 2
}

#Create the object
Expand Down
82 changes: 65 additions & 17 deletions main.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ param (
[Parameter(Mandatory=$true)]
[string]$ServerCfg,
[Parameter(Mandatory=$false)]
[switch]$UpdateCheck
[switch]$Task
)

#---------------------------------------------------------
Expand Down Expand Up @@ -63,7 +63,12 @@ Install-Dependency

Write-ScriptMsg "Importing Server Configuration..."
#Check if requested config exist in the config folder, if not, copy it from the templates. Exit if fails.
#In the case of an update check or alive check, remove the check if the configuration is deleted.
if (-not (Test-Path -Path ".\configs\$ServerCfg.psm1" -PathType "Leaf" -ErrorAction SilentlyContinue)) {
if($Task){
Unregister-Task
Exit
}
if (Test-Path -Path ".\templates\$ServerCfg.psm1" -PathType "Leaf" -ErrorAction SilentlyContinue){
$null = Copy-Item -Path ".\templates\$ServerCfg.psm1" -Destination ".\configs\$ServerCfg.psm1" -ErrorAction SilentlyContinue
} else {
Expand All @@ -82,18 +87,54 @@ catch {
#Parse configuration
Read-Config

#Check if script is already running
if(Get-Lock){
exit
}

#---------------------------------------------------------
# Checking if updates are available.
#---------------------------------------------------------
if ($UpdateCheck) {
Write-ScriptMsg "Checking on steamCMD if updates are avaiable for $($Server.Name)..."
if (-not (Request-Update)){
Write-ScriptMsg "No updates are available for $($Server.Name)"
Exit
}
Write-ScriptMsg "Updates are available for $($Server.Name), Proceeding with update process..."
#Run Launcher as usual if an update is required
#Locking Script to avoid double run
Lock-Process

#---------------------------------------------------------
# Checking Scheduled Task
#---------------------------------------------------------
if ($Task) {
$FullRunRequired = $false
Write-ScriptMsg "Running Tasks for $($Server.UID) ..."
$TasksSchedule = Get-TaskConfig

if(($Server.AutoRestartOnCrash) -and (($TasksSchedule.NextAlive) -lt (Get-Date))){
Write-ScriptMsg "Checking Alive State"
if(-not (Get-ServerProcess)) {
Write-ScriptMsg "Server is Dead, Restarting..."
Update-TaskConfig -Alive
$FullRunRequired = $true
} else {
Write-ScriptMsg "Server is Alive"
}
}

if(($Server.AutoUpdates) -and (($TasksSchedule.NextUpdate) -lt (Get-Date))){
Write-ScriptMsg "Checking on steamCMD if updates are avaiable for $($Server.UID)..."
if (Request-Update){
Write-ScriptMsg "Updates are available for $($Server.UID), Proceeding with update process..."
$FullRunRequired = $true
Update-TaskConfig -Update
} else {
Write-ScriptMsg "No updates are available for $($Server.UID)"
}
}

Write-ScriptMsg "Checking if server $($Server.UID) is due for restart"
if(($Server.AutoRestart) -and (($TasksSchedule.NextRestart) -lt (Get-Date))){
$FullRunRequired = $true
Update-TaskConfig -Restart
}

if(-not $FullRunRequired) {
exit
}
#Run Launcher as usual
}

#---------------------------------------------------------
Expand Down Expand Up @@ -142,12 +183,12 @@ if (-not $FreshInstall -and $Server.AutoUpdates) {
}

#---------------------------------------------------------
# Create Scheduled Task to monitor auto-updates
# Register Scheduled Task
#---------------------------------------------------------

if ($Server.AutoUpdates -and -not (Get-ScheduledTask -TaskName "UpdateCheck-$($server.Name)" -ErrorAction SilentlyContinue)) {
Write-ScriptMsg "Registering Update Check Scheduled Task for $($Server.Name)..."
Register-UpdateTask
if ($Server.AutoUpdates -and -not (Get-ScheduledTask -TaskName "Tasks-$($server.UID)" -ErrorAction SilentlyContinue)) {
Write-ScriptMsg "Registering Scheduled Tasks Check for $($Server.UID)..."
Register-Task
}

#---------------------------------------------------------
Expand Down Expand Up @@ -183,10 +224,17 @@ catch {
Exit-WithError -ErrorMsg "Unable clean old logs."
}


#---------------------------------------------------------
# Stop Logging
# Unlock Process
#---------------------------------------------------------

Unlock-Process

Write-ServerMsg "Script successfully completed."

#---------------------------------------------------------
# Stop Logging
#---------------------------------------------------------

Stop-Transcript
10 changes: 10 additions & 0 deletions templates/7daystodie.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,16 @@ $ServerDetails = @{
#Set to $true if you want this server to automatically update.
AutoUpdates = $true

#Set to $true if you want this server to automatically restart on crash.
AutoRestartOnCrash = $true

#Set to $true if you want this server to automatically restart at set hour.
AutoRestart = $true

#The time at which the server will restart daily.
#(Hour, Minute, Seconds)
AutoRestartTime = @(3,0,0)

#Process name in the task manager
ProcessName = "7DaysToDieServer"

Expand Down
10 changes: 10 additions & 0 deletions templates/astroneer.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,16 @@ $ServerDetails = @{
#Set to $true if you want this server to automatically update.
AutoUpdates = $true

#Set to $true if you want this server to automatically restart on crash.
AutoRestartOnCrash = $true

#Set to $true if you want this server to automatically restart at set hour.
AutoRestart = $true

#The time at which the server will restart daily.
#(Hour, Minute, Seconds)
AutoRestartTime = @(3,0,0)

#Process name in the task manager
ProcessName = "AstroServer-Win64-Shipping"

Expand Down
10 changes: 10 additions & 0 deletions templates/icarus.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ $ServerDetails = @{
#Set to $true if you want this server to automatically update.
AutoUpdates = $true

#Set to $true if you want this server to automatically restart on crash.
AutoRestartOnCrash = $true

#Set to $true if you want this server to automatically restart at set hour.
AutoRestart = $true

#The time at which the server will restart daily.
#(Hour, Minute, Seconds)
AutoRestartTime = @(3,0,0)

#Process name in the task manager
ProcessName = "IcarusServer-Win64-Shipping"

Expand Down
10 changes: 10 additions & 0 deletions templates/insurgencysandstorm.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@ $ServerDetails = @{
#Set to $true if you want this server to automatically update.
AutoUpdates = $true

#Set to $true if you want this server to automatically restart on crash.
AutoRestartOnCrash = $true

#Set to $true if you want this server to automatically restart at set hour.
AutoRestart = $true

#The time at which the server will restart daily.
#(Hour, Minute, Seconds)
AutoRestartTime = @(3,0,0)

#Process name in the task manager
ProcessName = "InsurgencyServer-Win64-Shipping"

Expand Down
10 changes: 10 additions & 0 deletions templates/killingfloor2.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,16 @@ $ServerDetails = @{
#Set to $true if you want this server to automatically update.
AutoUpdates = $true

#Set to $true if you want this server to automatically restart on crash.
AutoRestartOnCrash = $true

#Set to $true if you want this server to automatically restart at set hour.
AutoRestart = $true

#The time at which the server will restart daily.
#(Hour, Minute, Seconds)
AutoRestartTime = @(3,0,0)

#Process name in the task manager
ProcessName = "KFServer"

Expand Down
Loading

0 comments on commit be1df90

Please sign in to comment.