To add a time limit to a systemd service, use the TimeoutSec= directive in the [Service] section of the service file. This sets the maximum time systemd will wait for the service to start, stop, or complete its execution.
For startup time limits: Use
TimeoutStartSec=to limit how long systemd waits for the service to start. Example:TimeoutStartSec=300sets a 5-minute limit.For runtime limits: Starting with systemd 229, use
RuntimeMaxSec=to set a maximum duration for the service’s active state. Example:RuntimeMaxSec=1hstops the service after one hour.For stopping time limits: Use
TimeoutStopSec=to set how long systemd waits for the service to stop gracefully. Example:TimeoutStopSec=60allows 60 seconds.
Note: Avoid setting
TimeoutSec=infinityas it may block system shutdown indefinitely. Use a large but finite value instead.
To apply changes:
Create an override file:
sudo systemctl edit <service-name>Add the timeout settings under
[Service].Reload systemd:
sudo systemctl daemon-reloadRestart the service:
sudo systemctl restart <service-name>
For system-wide defaults, edit /etc/systemd/system.conf and adjust:
DefaultTimeoutStartSec=DefaultTimeoutStopSec=
My systemd service kept timing out because of how long it would take to boot up also, so this fixed it for me:
Edit your systemd file:
- For modern versions of
systemd: Runsystemctl edit --full node.service(replace "node" with your service name).- This will create a system file at
/etc/systemd/system/node.service.d/that will override the system file at/usr/lib/systemd/system/node.service. This is the proper way to configure your system files. More information about how to usesystemctl editis here.
- This will create a system file at
- Directly editing system file: The system file for me is at
/usr/lib/systemd/system/node.service. Replace "node" with your application name. However, it is not safe to directly edit files in/usr/lib/systemd/(See comments)
- For modern versions of
Use
TimeoutStartSec,TimeoutStopSecorTimeoutSec(more info here) to specify how long the timeout should be for starting & stopping the process. Afterwards, this is how my systemd file looked:[Unit] Description=MyProject Documentation=man:node(1) After=rc-local.service [Service] WorkingDirectory=/home/myproject/GUIServer/Server/ Environment="NODE_PATH=/usr/lib/node_modules" ExecStart=-/usr/bin/node Index.js Type=simple Restart=always KillMode=process TimeoutSec=900 [Install] WantedBy=multi-user.target- You can also view the current Timeout status by running any of these (but you'll need to edit your service to make changes! See step 1). Confusingly, the associated properties have a "U" in their name for microseconds. See this Github issue for more information:
systemctl show node.service -p TimeoutStartUSecsystemctl show node.service -p TimeoutStopUSecsystemctl show node.service -p TimeoutUSec
- You can also view the current Timeout status by running any of these (but you'll need to edit your service to make changes! See step 1). Confusingly, the associated properties have a "U" in their name for microseconds. See this Github issue for more information:
Next you'll need to reload the systemd with
systemctl reload node.serviceNow try to start your service with
systemctl start node.serviceIf that didn't work, try to reboot systemctl with
systemctl rebootIf that didn't work, try using the
--no-blockoption for systemctl like so:systemctl --no-block start node.service. This option is described here: "Do not synchronously wait for the requested operation to finish. If this is not specified, the job will be verified, enqueued and systemctl will wait until the unit's start-up is completed. By passing this argument, it is only verified and enqueued."- There is also the option to use
systemctl maskinstead ofsystemctl start. For more info see here.
- There is also the option to use
Updates from Comments:
TimeoutSec=infinity: Instead of using "infinity" here, put a large amount of time instead, likeTimeoutSec=900(15 min). If the application takes "forever" to exit, then it's possible that it will block a reboot indefinitely. Credit @Alexis Wilke and @JCCyC- Instead of editing
/usr/lib/systemd/system, trysystemctl editinstead or edit/etc/systemd/systemto override them instead. You should never edit service files in/usr/lib/. Credit @ryeager and @0xC0000022L
** Update from systemd source docs ** When specified "infinity" as a value to any of these timeout params, the timeout logic is disabled.
JobTimeoutSec=, JobRunningTimeoutSec=,TimeoutStartSec=, TimeoutAbortSec=
The default is "infinity" (job timeouts disabled), except for device units where JobRunningTimeoutSec= defaults to DefaultTimeoutStartSec=.
Reference: enter link description here
Similarly this logic applies to service level and laid out clearly in URL below. Reference: enter link description here
Answer from Katie on Stack ExchangeMy systemd service kept timing out because of how long it would take to boot up also, so this fixed it for me:
Edit your systemd file:
- For modern versions of
systemd: Runsystemctl edit --full node.service(replace "node" with your service name).- This will create a system file at
/etc/systemd/system/node.service.d/that will override the system file at/usr/lib/systemd/system/node.service. This is the proper way to configure your system files. More information about how to usesystemctl editis here.
- This will create a system file at
- Directly editing system file: The system file for me is at
/usr/lib/systemd/system/node.service. Replace "node" with your application name. However, it is not safe to directly edit files in/usr/lib/systemd/(See comments)
- For modern versions of
Use
TimeoutStartSec,TimeoutStopSecorTimeoutSec(more info here) to specify how long the timeout should be for starting & stopping the process. Afterwards, this is how my systemd file looked:[Unit] Description=MyProject Documentation=man:node(1) After=rc-local.service [Service] WorkingDirectory=/home/myproject/GUIServer/Server/ Environment="NODE_PATH=/usr/lib/node_modules" ExecStart=-/usr/bin/node Index.js Type=simple Restart=always KillMode=process TimeoutSec=900 [Install] WantedBy=multi-user.target- You can also view the current Timeout status by running any of these (but you'll need to edit your service to make changes! See step 1). Confusingly, the associated properties have a "U" in their name for microseconds. See this Github issue for more information:
systemctl show node.service -p TimeoutStartUSecsystemctl show node.service -p TimeoutStopUSecsystemctl show node.service -p TimeoutUSec
- You can also view the current Timeout status by running any of these (but you'll need to edit your service to make changes! See step 1). Confusingly, the associated properties have a "U" in their name for microseconds. See this Github issue for more information:
Next you'll need to reload the systemd with
systemctl reload node.serviceNow try to start your service with
systemctl start node.serviceIf that didn't work, try to reboot systemctl with
systemctl rebootIf that didn't work, try using the
--no-blockoption for systemctl like so:systemctl --no-block start node.service. This option is described here: "Do not synchronously wait for the requested operation to finish. If this is not specified, the job will be verified, enqueued and systemctl will wait until the unit's start-up is completed. By passing this argument, it is only verified and enqueued."- There is also the option to use
systemctl maskinstead ofsystemctl start. For more info see here.
- There is also the option to use
Updates from Comments:
TimeoutSec=infinity: Instead of using "infinity" here, put a large amount of time instead, likeTimeoutSec=900(15 min). If the application takes "forever" to exit, then it's possible that it will block a reboot indefinitely. Credit @Alexis Wilke and @JCCyC- Instead of editing
/usr/lib/systemd/system, trysystemctl editinstead or edit/etc/systemd/systemto override them instead. You should never edit service files in/usr/lib/. Credit @ryeager and @0xC0000022L
** Update from systemd source docs ** When specified "infinity" as a value to any of these timeout params, the timeout logic is disabled.
JobTimeoutSec=, JobRunningTimeoutSec=,TimeoutStartSec=, TimeoutAbortSec=
The default is "infinity" (job timeouts disabled), except for device units where JobRunningTimeoutSec= defaults to DefaultTimeoutStartSec=.
Reference: enter link description here
Similarly this logic applies to service level and laid out clearly in URL below. Reference: enter link description here
Running systemctl show SERVICE_NAME.service -p TimeoutStopUSec I could at least see the timeout set by systemd to my service.
I changed the script to a regular unit file one in order for it work properly.
TimeoutStartSec should be used. As @muru mentioned in the comment, the correct way to run a script that should exit is to use Type=oneshot instead of Type=simple.
For example, if your script is normally executed in under 10 seconds, your config would be:
[Service]
Type=oneshot
TimeoutStartSec=10
SyslogIdentifier=myservice
Environment='MYVAR=myvar'
User=deanresin
ExecStart=/usr/bin/python3 /home/deanresin/myscript
If the script takes more than 10 seconds to execute, it will be killed, and the service would show as failed.
Since systemd 229 (2016-02-11), the RuntimeMaxSec option can be used. This does not require (or even work with) Type=oneshot as it sets a time limit for the "active" state instead of "activating".
Hey all, I was reading up on the systemd timeout parameters in the system.conf file (/etc/systemd/system.conf) and was curious if anyone has any input as to problems that can arise if we set the #DefaultTimeoutStopSec=90s to something like 5 seconds rather than letting it stay at 90 seconds.
This is something I do from time to time on systems if I get an SDDM timeout when shutting down the PC and never have had a problem but wondered if it could cause an issue other than the journal not logging.
systemctl daemon-reexec should solve your problem.
there are only a few properties that you can set thru "set-property" command.
you can get a version of your systemd thru command:
systemctl --version
then you need to update it to get latest commands like "cat" with:
sudo yum update systemd -y
after that you can see stuff that overrides your DefaultTimeoutStartSec=90s run:
systemctl cat <service>
Then you need to create a {service}.service file to override your settings with information from [Service] section from systemctl cat {service} command and restart daemon after that:
echo "[Service]
TimeoutSec=15min
ExecStart=/etc/rc.d/init.d/<service> start
ExecStop=/etc/rc.d/init.d/<service> stop
ExecReload=/etc/rc.d/init.d/<service> reload" > /lib/systemd/system/{service}.service
sudo systemctl daemon-reload
Partial solution. I basically set these values
StartLimitIntervalSec=1d
StartLimitBurst=5
Which limits 5 restarts per day.
You can specify
StartLimitIntervalSec=infinity
but please read the documentation for when the restart counter is reset.
Additionally it is reported that system reboot and systemctl daemon-reload also reset the counter.
To have a service restart 3 times at 90 second intervals include the following lines in your systemd service file:
[Unit]
StartLimitIntervalSec=400
StartLimitBurst=3
[Service]
Restart=always
RestartSec=90
Before systemd-230 it was called just StartLimitInterval:
[Unit]
StartLimitInterval=400
StartLimitBurst=3
[Service]
Restart=always
RestartSec=90
This worked worked for me for a service that runs a script using Type=idle. Note that StartLimitIntervalSec must be greater than RestartSec * StartLimitBurst otherwise the service will be restarted indefinitely.
It took me some time with a lot of trial and error to work out how systemd uses these options, which suggests that systemd isn't as well documented as one would hope. These options effectively provide the retry cycle time and maximum retries that I was looking for.
References: https://manpages.debian.org/testing/systemd/systemd.unit.5.en.html for Unit section https://manpages.debian.org/testing/systemd/systemd.exec.5.en.html for Service section
Some years later and with systemd 232 it dosn't work anymore as described in the question and in the answers from 2016. Option name StartLimitIntervalSec and Sections have changed. Now it has to look like this example:
[Unit]
StartLimitBurst=5
StartLimitIntervalSec=33
[Service]
Restart=always
RestartSec=5
ExecStart=/bin/sleep 6
This will do 5 restarts in 30 sec (5*6) plus one restart in 33 sec. So we have 6 restarts in 33 sec. This exceeds the limit of 5 restarts in 33 sec. So restarts will stop at 5 counts after about 31 sec.
It is possible to terminate systemd services after a certain amount of time.
Use the RuntimeMaxSec option for Type=simple services:
[Unit]
Description=Terminate simple Service Test
[Service]
Type=simple
RuntimeMaxSec=5
ExecStart=/bin/sleep 10
Use the TimeoutStartSec for Type=oneshot services:
[Unit]
Description=Terminate oneshot Service Test
[Service]
Type=oneshot
TimeoutStartSec=5
ExecStart=/bin/sleep 10
Both services will be terminated after 5 seconds before the sleep timer reaches 10 seconds.
Details on RuntimeMaxSec and TimeoutStartSec can be found here:
https://www.freedesktop.org/software/systemd/man/systemd.service.html
I believe you can add the following to the service file's [Unit] directives:
JobTimeoutSec=43200
You could probably just write a wrapper script to terminate the process after 12 hours or use timeout 12h COMMAND [ARG]...
The mappings of systemd limits to ulimit
Directive ulimit equivalent Unit
LimitCPU= ulimit -t Seconds
LimitFSIZE= ulimit -f Bytes
LimitDATA= ulimit -d Bytes
LimitSTACK= ulimit -s Bytes
LimitCORE= ulimit -c Bytes
LimitRSS= ulimit -m Bytes
LimitNOFILE= ulimit -n Number of File Descriptors
LimitAS= ulimit -v Bytes
LimitNPROC= ulimit -u Number of Processes
LimitMEMLOCK= ulimit -l Bytes
LimitLOCKS= ulimit -x Number of Locks
LimitSIGPENDING= ulimit -i Number of Queued Signals
LimitMSGQUEUE= ulimit -q Bytes
LimitNICE= ulimit -e Nice Level
LimitRTPRIO= ulimit -r Realtime Priority
LimitRTTIME= ulimit -R Microseconds
If a ulimit is set to 'unlimited' set it to 'infinity' in the systemd config
ulimit -c unlimited is the same as LimitCORE=infinity
ulimit -v unlimited is the same as LimitAS=infinity
ulimit -m unlimited is the same as LimitRSS=infinity
So a final config would look like
[Unit]
Description=Apache Solr
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
WorkingDirectory=/opt/solr/server
User=solr
Group=solr
LimitAS=infinity
LimitRSS=infinity
LimitCORE=infinity
LimitNOFILE=65536
ExecStart=/opt/solr/bin/solr-foo
Restart=on-failure
SuccessExitStatus=143 0
SyslogIdentifier=solr
[Install]
WantedBy=multi-user.target
In this particular case, I don't know the full java path (since it changes based on server type), and systemd isn't happy about relative paths, I wrap the java command in a simple bash script located at /opt/solr/bin/solr-foo
#!/bin/bash
. /opt/solr/bin/solr.in.sh
# Load $JAVA_HOME from 1 of 2 places where it could be defined
# Last one wins
if [[ -f "/etc/profile.d/jdk.sh" ]]; then
. /etc/profile.d/jdk.sh
fi
if [[ -f "/etc/profile.d/zing.sh" ]]; then
. /etc/profile.d/zing.sh
fi
exec ${JAVA_HOME}/bin/java -server \
-Djetty.port=${SOLR_PORT} \
${SOLR_JAVA_MEM} \
${GC_TUNE} \
${GC_LOG_OPTS} \
-DzkClientTimeout=${ZK_CLIENT_TIMEOUT} \
-DzkHost=${ZK_HOST} \
-DSTOP.PORT=7900 \
-DSTOP.KEY=foobar \
-Dhost=${SOLR_HOST} \
-Duser.timezone=${SOLR_TIMEZONE} \
-Djetty.home=/opt/solr/server \
-Dsolr.solr.home=${SOLR_HOME} \
-Dsolr.install.dir=/opt/solr \
-Dlog4j.configuration=file:/var/solr/log4j.properties \
-Xss256k \
-Dbootstrap_conf=true \
-Dbootstrap_confdir=/opt/solr/server/solr/configsets/foobar/conf \
-Dcollection.configName=foobar \
-jar start.jar --module=http
The syntax for setting the limits you asked for is:
# Equivalent of ulimit -c 2
LimitCORE=2
# Functional replacement for both ulimit -m and ulimit -v
MemoryMax=1024M
The equivalent of ulimit -v is LimitAS, however, the systemd documentation states "Don't use. This limits the allowed address range, not memory use! Defaults to unlimited and should not be lowered. To limit memory use, see MemoryMax= in systemd.resource-control(5)".
The equivalent of ulimit -m is LimitRSS, however, the systemd documentation states "Don't use. No effect on Linux." and further explains "Note that most process resource limits configured with these options are per-process, and processes may fork in order to acquire a new set of resources that are accounted independently of the original process, and may thus escape limits set. Also note that LimitRSS= is not implemented on Linux, and setting it has no effect. Often it is advisable to prefer the resource controls listed in systemd.resource-control(5) over these per-process limits, as they apply to services as a whole, may be altered dynamically at runtime, and are generally more expressive. For example, MemoryMax= is a more powerful (and working) replacement for LimitRSS=.".
The full list of systemd equivalents of ulimit is listed here: https://www.freedesktop.org/software/systemd/man/systemd.exec.html#Process%20Properties
MemoryMax, from systemd resource control documentation: https://www.freedesktop.org/software/systemd/man/latest/systemd.resource-control.html#MemoryMax=bytes