Как проверить, находится ли временная метка «дата-время» между двумя временными метками «дата-время»

Как отметил heemayl в комментарии, справочная страница отвечает на ваш вопрос. Из Интернета:

Wants=

A weaker version of Requires=. Units listed in this option will be started if the configuring unit is. However, if the listed units fail to start or cannot be added to the transaction, this has no impact on the validity of the transaction as a whole. This is the recommended way to hook start-up of one unit to the start-up of another unit.

И

Requires=

Configures requirement dependencies on other units. If this unit gets activated, the units listed here will be activated as well. If one of the other units gets deactivated or its activation fails, this unit will be deactivated. This option may be specified more than once or multiple space-separated units may be specified in one option in which case requirement dependencies for all listed names will be created. Note that requirement dependencies do not influence the order in which services are started or stopped. This has to be configured independently with the After= or Before= options. If a unit foo.service requires a unit bar.service as configured with Requires= and no ordering is configured with After= or Before=, then both units will be started simultaneously and without any delay between them if foo.service is activated. Often, it is a better choice to use Wants= instead of Requires= in order to achieve a system that is more robust when dealing with failing services.

Note that this dependency type does not imply that the other unit always has to be in active state when this unit is running. Specifically: failing condition checks (such as ConditionPathExists=, ConditionPathExists=, … — see below) do not cause the start job of a unit with a Requires= dependency on it to fail. Also, some unit types may deactivate on their own (for example, a service process may decide to exit cleanly, or a device may be unplugged by the user), which is not propagated to units having a Requires= dependency. Use the BindsTo= dependency type together with After= to ensure that a unit may never be in active state without a specific other unit also in active state (see below).

Со страницы freedesktop.org

Ваша служба запустится, только если multi -user.target будет достигнуто (Я не знаю, что произойдет, если вы попытаетесь добавить его к этой цели? ), и systemd попытается запустить display -manager.service перед вашим сервисом. Если display -manager.service по какой-либо причине не работает, ваша служба все равно будет запущена (, поэтому, если вам действительно нужен менеджер display -, используйте Requires=для этого ). Однако, если multi -user.target не достигнут, ваша служба не будет запущена.

Чем ты занимаешься? Это киосковая система? Интуитивно я бы предположил, что вы хотите добавить свой сервис в мульти -user.target (, чтобы он запускался при запуске )и строго зависел от display -manager.service через Requires=display-manager.service. Но сейчас это только дикие догадки.

1
20.12.2019, 17:53
1 ответ

Конкретно с bash это должно быть просто:

start='2019-11-11 17:02:54,479'
end='2019-11-12 05:13:55,998'
date='2019-11-11 19:05:55,823'

if LC_ALL=C command eval '[[ ! $date < $start && ! $date > $end ]]'; then 
  echo the date is in the range
fi

Это лексическое сравнение. Это работает, потому что в локали C эти представления даты сортируются одинаково лексически и хронологически.

Операторы

bash's [[ < / > ]]используют strcoll()для сравнения строк,поэтому используйте алгоритм сопоставления локализации. В локали C strcoll()должен работать как strcmp(). В других локалях он сравнивается в соответствии с соглашениями локали, поэтому вы не можете гарантировать результат.

Для POSIX можно использовать:

if LC_ALL=C expr "x $date" '>=' "x $start" '&' "x $date" '<=' "x $end" > /dev/null; then
  echo the date is in the range
fi

Теперь, если вы обрабатываете файлы журналов, вы, вероятно, захотите провести это сравнение с awk. Предполагая, что метки времени находятся в начале каждой строки:

LC_ALL=C awk -v start='2019-11-11 17:02:54,479' \
             -v end='2019-11-12 05:13:55,998' '
   $0 >= start && $0 <= end' < file.log

напечатает строки, начинающиеся с метки времени в этом диапазоне.

1
27.01.2020, 23:40

Теги

Похожие вопросы