- Thread: cron + notify send
- cron + notify send
- Re: cron + notify send
- Re: cron + notify send
- Re: cron + notify send
- Re: cron + notify send
- Re: cron + notify send
- Re: cron + notify send
- Re: cron + notify send
- Re: cron + notify send
- Re: cron + notify send
- Notify-send не работает от crontab
- 10 ответов
- Linux Mint Forums
- [Mint 18, 19] Using notify-send from a user crontab
- [Mint 18, 19] Using notify-send from a user crontab
- Кукушка на bash своими руками
- Уведомления в Ubuntu
- Задачи по расписанию в linux
- Диалоги в скриптах linux
- В итоге, вот что получилось
- Sending Desktop Notification from Cron
Thread: cron + notify send
Thread Tools
Display
cron + notify send
I can’t get cron to work out a notify send.
Cron creates an empty ‘check.log’ in my home directory but still doesn’t display notify-send.
I’ve checked the ‘notify-send script’ manually and it works.
Re: cron + notify send
I had the same problem before.. and then I enabled X ACL for localhost to connect to GUI applications.
$ xhost +local:
non-network local connections being added to access control list
$ xhost
access control enabled, only authorized clients can connect
LOCAL:
.
Re: cron + notify send
Also, there is no need of «DISPLAY=0.0» in your Alarm.sh, as you’ll be giving it from cron.
& with notify-send «expire time» doesn’t work yet. No Matter what you do, that notification will stay on your screen
PS: if you’re getting work expire-time somehow.. please let me know.
Re: cron + notify send
also, any reason why you’re running this from roots crontab (sudo crontab) rather than your own user’s crontab? As root you won’t have the correct DBUS_SESSION_BUS_ADDRESS set that you would need to send the notification to your users gnome session, so I don’t think your notify-send command will work.
Re: cron + notify send
i disabled the ‘sudo’ command and got it working perfectly, awesome. thanks!
Re: cron + notify send
Also, there is no need of «DISPLAY=0.0» in your Alarm.sh, as you’ll be giving it from cron.
& with notify-send «expire time» doesn’t work yet. No Matter what you do, that notification will stay on your screen
PS: if you’re getting work expire-time somehow.. please let me know.
no wonder it stayed a little too long
Re: cron + notify send
It is possible to enable the timeout (-t) option but it requires replacing notify-send with a ppa package that a user rebuilt with the fix. I did that and it works. The ppa is leolik
The all-knowing Ubuntu devs have decided that they don’t want to support -t so other than this you’ll not see it supported any time soon.
Re: cron + notify send
yes, you’re right DBUS_SESSION_BUS_ADDRESS variable is unavailable in root environments. But, I wonder notify-send with my root cron is working perfectly. I know this because, This is because I run some cron for regular data backup & kill processes at specific time as root & to notify that task successfully completed, I use notify-send.
Last edited by Rushyang; April 14th, 2011 at 12:19 PM .
Re: cron + notify send
I also wonder, is there any way to work with zenity via crons??
EDIT:
well, I just simply figured out if we add «DISPLAY=:0.0» line as prefix before calling any GTK+ dialogs (through zenity) even in scripts. They works just fine.
Last edited by Rushyang; April 23rd, 2011 at 06:49 PM .
Re: cron + notify send
the dbus session variable problem can be gotten around . ie. even if you are root you can figure out the right value for a logged in user and set that value in your own environment such that notify-send appears on the user’s desktop.
you pgrep for the users nautilus session, or gnome-panel, etc, ie. some process that is sure to running if that user is logged in, then from the pid grab the variable from the /proc/
Источник
Notify-send не работает от crontab
Я сделал сценарий, который должен уведомить меня, когда появится новая глава манги, которую я читаю. Я использовал команду notify-send для этого. Программа работает, когда я пытаюсь запустить ее в терминале. Появляется уведомление. Однако, когда я разместил это в своем crontab, уведомление не отображается. Я уверен, что программа работает с тех пор, как я создал файл для меня. Файл был создан, но уведомление не появилось.
И вот что я написал в своем crontab
10 ответов
Кажется, что в версии 13.04, по крайней мере, в Gnome Shell, все по-другому.
Во-первых, это то, что env печатает при запуске из задания cron zzyxy (не root): [ ! d1]
Чтобы заставить notify-send работать, кажется, необходимо установить переменную среды DBUS_SESSION_BUS_ADDRESS, в соответствии с комментарием DahitiF на ubuntuforums.org. Просто добавьте следующее к вашему фактическому описанию работы:
Кажется, что не нужно устанавливать DISPLAY.
Команда notify-send не будет отображать сообщение на вашем экране при запуске cron. Просто добавьте целевой экран вверху вашего скрипта, например:
Для Ubuntu 14.04, по крайней мере, ответ klrmr выше — правильный ответ. Кажется, что не нужно устанавливать DISPLAY или формулировать полные пути для уведомления-отправки или что-либо иное, как правило, в $ PATH.
Ниже приведен сценарий cron, который я использую для выключения виртуальной машины, когда состояние батареи ноутбука становится слишком низким. Настройка линии DBUS_SESSION_BUS_ADDRESS в ответе klrmr выше — это модификация, которая, наконец, правильно обработала предупреждения.
Первым виновником является ваш файл crontab, вам также нужно указать имя пользователя, с которым должен выполняться сценарий, лучше сохранить его как root
, а затем вы должны использовать имя пользователя пользователь GUI внутри сценария и добавьте его для уведомления-отправки с помощью «sudo или su» для выполнения команды как пользователя, которому принадлежит пример GUI
где gnome_user_name является именем пользователя, который запустил сеанс GUI, это вы вошли в систему, и если вы хотите сделать его динамическим выбором, вы можете получить его из
Источник
Linux Mint Forums
Welcome to the Linux Mint forums!
[Mint 18, 19] Using notify-send from a user crontab
[Mint 18, 19] Using notify-send from a user crontab
Post by rene » Sat Oct 06, 2018 7:26 pm
Since I’ve wanted to do so a few times I expect the following may be useful to some. Current as of Mint 18 and 19.
Employing the desktop notification mechanism from the command line is a matter of installing libnotify-bin if it isn’t yet installed and invoking e.g. notify-send -u critical -i dialog-warning «summary» «optional text» . The «-u critical» keeps the notification on screen until manually closed, the «-i dialog-warning» selects a notification icon as could be chosen from among for example the «Standard Status Icons» section of https://standards.freedesktop.org/icon- . atest.html
Doing so from a user crontab does not however work: notify-send communicates over the dbus session bus but cron jobs are not part of any graphical user session; are not provided the session bus address of whichever graphical session runs the desktop notifier to be contacted. For Mint 19 and supposedly Ubuntu 18.04 this is easily remedied by manually providing the cron job with the DBUS_SESSION_BUS_ADDRESS=»unix:path=/run/user/$(id -u)/bus» environment variable but that socket does not in fact exist on Mint 18 and supposedly Ubuntu 16.04.
On Mint 18 the first idea might be to source
/.dbus/session-bus/$(dbus-uuidgen —get)-0, in which «0» is the X display number as in principle available via loginctl similarly to the below, but when a new session bus launches — as can happen for any number of reasons — that file will describe the new bus, not the «main» user session bus that notify-send needs to communicate with the desktop notifier.
In absence of the socket as available from under /run/user for Mint 19 the somewhat unfortunate thing to do is look at the environment of some user graphical session process so as to retrieve DBUS_SESSION_BUS_ADDRESS. Hardcoding e.g. «gnome-session» as said process is the usual thing to do but with logind there’s a slightly more elegant method available: get the session identifier for the «Display» session from loginctl show-user , its «Leader» from loginctl show-session and its oldest child with pgrep -o -P ; that oldest child will in normal setups be the desktop session manager and have the correct DBUS_SESSION_BUS_ADDRESS.
As code: you would replace a call of notify-send in a user crontab with a call of, e.g., the executable shell script
Note that the described method, the «else» branch in the above, works on Mint 19 as well as Mint 18 but that we clearly needn’t bother if we have the socket available from under /run/user. Also, that the —value parameter to loginctl as available on Mint 19 and allowing to forego cut is not available on Mint 18.
If the user is not in fact logged in this exits gracefully without notifying anything, and it is hoped that this method may survive a few versions.
Источник
Кукушка на bash своими руками
Для организации моей работы удобно видеть или слышать уведомления о том, что прошел час, полчаса и т.д. Это нужно мне для ориентации во временном пространстве и правильного планирования своей работы.
Поскольку у меня стоит Ubuntu, то и статья будет про то, как сделать такие уведомления стандартными средствами Ubuntu.
Итак, мне нужно:
- каждый час видеть и слышать уведомление о времени
- уведомление не должно отвлекать
- решение должно быть легким и экономным с точки зрения ресурсов
В процессе поиска перепробовал несколько приложений. Некоторые из них были неплохи, но без нужного мне функционала, некоторые — ужасно неудобны, а что-то — вообще не работало. Почти у всех программ сильно страдала надежность работы.
Нормального инструмента я так и не нашел, и поэтому решил реализовать его сам. Писать свою программу — долго, а потому проще сделать скрипт на коленках.
Уведомления в Ubuntu
Как известно, для уведомлений в Ubuntu применяется утилита notify-send. В последних версиях Ubuntu notify-send используется как основное средство уведомлений. Это действительно очень удобно, когда все сообщения показываются однообразно. Пользоваться ей так:
Запустив эту несложную команду в консоли, вы через некоторое время увидите уведомление с заголовком title и сообщением message. У меня это выглядит так:
Отлично, выводить сообщения мы уже умеем, осталось научиться показывать их по расписанию.
Задачи по расписанию в linux
Для задач по расписанию есть в linux отличное средство crontab
отрывается редактор, вбиваем в него строку:
Сохраняем, любуемся результатом. Если хочется поиграться, то можно поставить уведомления раз в минуту, тогда отладочная запись будет выглядеть как-то так:
Теперь через равные промежутки времени мы можем что-нибудь выводить пользователю:
Для пользователей, не умеющих настраивать crontab могу посоветовать online генератор. Например, такой.
Отмечу отдельно, что я не стал возиться с определением номера дисплея. Да, он может меняться, но за несколько месяцев работы у меня он не разу не поменялся, т.к. у меня все-таки десктоп, а скрипт все-таки сделан на коленке.
Поделюсь ещё одним рецептом. Пользоваться crontab -e не очень удобно, т.к. открывается редактор по умолчанию. Обычно это nano. По-моему он ужасен. Я обычно делаю так:
Открывается файл в удобном gedit, редактируется, сохраняется или не сохраняется. После закрытия окна gedit настройки попадают в crontab.
Или оформляем все это дело в скрипт и кладем, например, на рабочий стол:
Диалоги в скриптах linux
Теперь, частично проблема была решена. Но только частично, ведь я не всегда смотрю на экран монитора и могу пропустить сообщение. На помощь мне пришла утилита zenity. Она также уже была в системе. Пишем смело в crontab
или отладочная запись:
В итоге получилось что-то типа такого:
Какое-то время работать было удобно, но со временем окно-уведомление стало меня доставать. Этот факт заставил меня модернизировать свои крон-скрипты. В итоге я наткнулся на 3-ю полезную утилиту: ESpeak.
Она позволяет синтезировать речевые сообщения на разных языках.
Добавляем новую строчку в crontab:
или отладочная строка
В итоге, вот что получилось
Синтезатор речи по-русски говорил ужасно. Слушать было противно, и поэтому я переключился на английский и сделал ещё ряд доработок:
- заставил часовщика говорить ещё и время
- добавил напоминания о том, что нужно попить кофе.
Конечный функционал уведомлений меня полностью устроил. Мне не пришлось ничего ставить, все было легковесным и надежным.
Мой файл crontab сейчас выглядит так:
Я вынес скрипты в файл hours.sh из-за того, что crontab скрипт не поддерживает обработку машинописного обратного апострофа. Если же вы в crontab укажете машинописный обратный апостроф, то скрипт в указанное время не сработает.
Ну и под конец скрины того, как это выглядит у меня.
Каждый час выводится сообщение сколько времени:
Сообщение дублируется звуком. Если я рядом с компьютером, я его услышу. И два раза в день мне отправляется напоминание о том, что нужно все-таки передохнуть.
UPD: Доработал скрипт на основе советов и комментариев.
В итоге, получилась новая версия hours.sh:
Скрипт вполне сносно сообщает по-русски о времени.
Источник
Sending Desktop Notification from Cron
Usually when one wants to keep track of one’s cron jobs, one tells the cron daemon to email the output of the commands. While this is probably the best solution for servers, on desktop machines is problematic. Many ISPs block outgoing traffic on port 25 (SMTP), and if you want to send the emails via external SMTP server (such as GMail) this requires you to store authentication details in plain text. A better solution for the desktop would be to harness the desktop notifications available in Ubuntu.
There is a useful tool called notify-send which is able to send desktop notifications directly from the command line. However, there are few caveats:
- notify-send expects its input on the command line, it can’t read from stdin .
- If you run from cron you must tell it which display to use.
The first issue can be worked around by using cat to pick up the input. The second issue is handled by adding a DISPLAY environment variable to the crontab. So your crontab will look something like this:
The first argument to notify-send is the title of the notification. The second is the actual text to appear in it, in our case it’s whatever comes in the stdin . If you want to store the output in a log file as well as displaying it in a desktop notification, you can use tee , which basically saves its input to a given file and also pipes it again to stdout .
Источник