How to run a function when publish posts? [duplicate]

Unless you have a very specific reason, and you know what you are doing, code like this belongs in the functions.php file or a dedicated plugin.

WordPress uses two kinds of hooks to allow certain functions to be triggered at specific times. These are called Actions and Filters.
https://codex.wordpress.org/Plugin_API

Placing code in a file that is never called, as you have described, will not allow your function to be registered for action. WordPress will not know this callback function is ready to run at a certain point.

Using the parameters given in your question, your solution is to place the following into your theme’s functions.php file or in a dedicated plugin:

function dothisfunction() {
    // Do stuff
}
add_action( 'publish_post', 'dothisfunction' );

WordPress will execute the code inside your function every time the publish_post action fires, but only if it sees your code. Complete reference for the publish_post action here: https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post